【问题标题】:How to dynamic load Jquery inside a JavaScript Class constructor and proceed the execution only after jquery has been fully loaded如何在 JavaScript 类构造函数中动态加载 Jquery 并仅在 jquery 完全加载后继续执行
【发布时间】:2019-10-12 08:53:33
【问题描述】:

这实际上是三个不同问题的合并,已经在堆栈溢出时得到了很好的回答!

1 - 如何Dynamic Load a JavaScript file from inside a Js Script

2 - 如何Dynamic Load Jquery

3 - SetTimeout inside a JS Class using this

基本上,我正在构建一个类,它将在我的客户网站中注入一些页面。

为此,客户端只需在页面上添加我的脚本 src。

<script src="<my_pub_http_address>/MyClass.js">

一旦脚本被调用,我将需要 jquery 来继续执行! 但是,我不知道调用脚本的网站是否已经加载了 jquery。

所以,我需要检查是否加载了 jquery,如果没有,我将不得不加载它,追加到头部,只有当 jquery 加载并工作时,我才会继续执行脚本。

PS:这是一种遗留答案!我事先已经有了解决方案! 因此,任何改进都会受到赞赏!

【问题讨论】:

  • 你到底为什么需要上课?
  • 我猜它涉及到一个关于如何知道 jQuery 何时完成的 Promise。但这很棘手,因为您的注入实际上只知道 DOM 注入何时完成,而不是从该 DOM 注入加载的脚本。您可以有一个 setTimeout 循环并检查 jQuery 对象是否存在。但不确定如何在 jQuery 对象存在之前使您的类不可用。我想您可以检查“isReady”上的每个方法,在 jQuery 加载之前返回 false。
  • 另外,“只有这样它才会执行”是什么意思?这个脚本是否只在最初加载时运行一次,而不是从其他任何地方调用?如果是这种情况,只需循环直到加载,然后继续。但是想办法做到这一点,实际上并不会停止整个页面的加载,因为那样会很粗鲁。
  • promises.. async / await.. 这个问题不是问题
  • @Anthony :你被纠正了...... setTimeout 是我需要的......也是前置而不是附加!!!

标签: javascript jquery html


【解决方案1】:

这就是我找到的解决方案:

// MyClass.js

var counterLoopLoad = 0;

class MyClass {

    constructor(){
        // do the code that does not need jQuery
        return this.Init()
    }

    JqueryLoader() {
        // Loop Breaker
        counterLoopLoad ++;

        if (counterLoopLoad == 100) {
            throw 'I need jQuery in order to do what I am suppose to do!';
        }

        var __jquery = document.createElement('script');
        __jquery.src = "http://code.jquery.com/jquery-latest.min.js";
        __jquery.type = 'text/javascript';

        // if needed ....
        // __jquery.onload = function() {
        //     some code here
        //
        // };

        // must be prepend !!! append won't work !!!!
        document.head.prepend(__jquery);

        // here is the point that makes all work !!!!
        // without setTimeOut, the script will get in a loop !

        var that = this;
        setTimeout(function () {
            that.Init();
        }, 500);
    }

    Init() {
        if (typeof jQuery == 'undefined') {
            return this.JqueryLoader();
         }

         jQuery.ajax(...);        
    }
}

【讨论】:

  • 为什么不直接做if (jQuery != defined)
  • 另外,您不应该通过$.ajax 进行检查,因为即使加载了jQuery,它也可能没有使用$ 对象作为命名空间。当其他库已经在使用$ 时,可能会发生这种情况。如果您要使用 ajax 调用,请使用 jQuery.ajax(...);
  • @Anthony 。你又说对了!!!我使用了 try/catch,因为该 ajax 是此类中唯一需要的 Jquery。在这种非常具体的情况下,我的事情并没有什么不同。我将使用您的提示检查和测试代码,然后我可以编辑答案!谢谢!
猜你喜欢
  • 2016-10-11
  • 2015-09-03
  • 2011-07-25
  • 1970-01-01
  • 1970-01-01
  • 2016-07-24
  • 1970-01-01
  • 2017-08-01
  • 2012-02-10
相关资源
最近更新 更多