简体   繁体   English

动态加载脚本时构造javascript和延迟执行

[英]Structure javascript and delay execution when dynamically loading scripts

I'm loading my javascript files using Modernizr.load() . 我正在使用Modernizr.load()加载我的javascript文件。 Now lets say each page needs to call their own init method after everything has finished loading. 现在让我们说每个页面都需要在所有内容加载完成后调用自己的init方法。 But I put the loading in a template master, which is unaware of the child pages. 但我把加载放在模板主文件中,它不知道子页面。 How can the pages know when the dependencies have finished loading? 页面如何知道依赖关系何时完成加载?

script 脚本

Page1Stuff= {
   init: function(){ alert('page 1 executed'); }
}
Page2Stuff= {
   init: function(){ alert('page 2 executed'); }
}

site master template 网站主模板

//Modernizr loads the script.
Modernizr.load([{
    load: 'jquery.js',
},
{
    load: 'script.js'
}]);

page1 第1页

$(function() {
    Page1Stuff.init();
});

page2 第2页

$(function() {
    Page2Stuff.init();
});

I think I see 2 problems here. 我想我在这里看到了两个问题。 If modernizr is still loading jquery, $ may not be defined. 如果modernizr仍在加载jquery,则可能无法定义$。 Also, Page2Stuff or Page1Stuff may not be defined. 此外,可能无法定义Page2StuffPage1Stuff

In your template: Use the modernizer "complete" call back to emit a custom event to signal the loading is complete, also set a global variable saying that the scripts have been loaded. 在您的模板中:使用现代化程序“完成”回调来发出自定义事件以指示加载完成,还设置一个全局变量,表示脚本已加载。

In your page scripts: first check the global variable to see if all scripts have been loaded, if not, register a handler to listen for the custom event you emit when the loading completes. 在页面脚本中:首先检查全局变量以查看是否已加载所有脚本,如果没有,则注册处理程序以侦听加载完成时发出的自定义事件。

In your template code: 在您的模板代码中:

// A simple object that calls its listeners when modernizer script loading completes.
global_scriptLoadingMonitor = (function() {
   var listeners = [];
   var isComplete = false;
   return {
      "addListener": function (listener) {
         listeners[listeners.length] = listener;
      },
      "complete": function () {
         isComplete = true;
         for (var i = listeners.length - 1; i >= 0; i--) {
            listeners[i]();
         }
      },
      "isComplete": isComplete
   }
})();

Modernizr.load([{
    load: 'jquery.js',
},
{
    load: 'script.js'
    complete: function () {
    {
       global_scriptLoadingMonitor.complete();
    }
}]);

Now in your Page1 do this: 现在在你的Page1执行此操作:

if (global_scriptLoadingMonitor.isComplete) {
    $(function() {
        Page1Stuff.init();
    });
} else {
    global_scriptLoadingMonitor.addListener(function() {
        $(function() {
           Page1Stuff.init();
        });
    });
}

And similarly for page2. 同样适用于page2。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM