jQuery's getScript - including files into the main scope?

泄露秘密 提交于 2019-12-07 21:54:38

问题


I have thought a lot about how I should include files in my backbone.js-application. In production, I am obviously going to join my files and minimize them to keep requests at a minimum, but during development, it would be nice to just have all files loaded and not having to call a buildscript for every little change.

So I have taken a look at jQuery's getScript()-method. I tried it out and were able to load my files.

As I've put the getScript-call into a function, to ensure that files are loaded before I initiate my backbone.js application, it appears that every script loaded, are not included into the global scope.

var loader = function () {
     var scripts = ['/app/routers/myrouter.js'];

     for (var i = 0; i < scripts.length; i++) {
         $.getScript(scripts[i], function () {});
     }

     console.log(myrouter); // Works - myrouter is a function
     init(); // Callback - we've loaded all scripts
 };

var init = function () {
    console.log(myrouter); // myrouter is undefined
};

$(document).ready(loader());

回答1:


Well first of all, you are just calling loader() instead of passing the function:

$(document).ready(loader);

Will fix that

Secondly, you are calling the init callback right away instead of when all the scripts are loaded. If there are many scripts you need to use promises:

    var scripts = ['/app/routers/myrouter.js'];
    for (var i = 0; i < scripts.length; i++) {
        scripts[i] = $.getScript(scripts[i]);
    }


    $.when.apply( $, scripts ).then( init, function(){
        "some script failed";
    });

The syntax used above is $.when( promise1, promise2, ...).then( successCallback, failureCallback) - we fill the array with promises and use .apply to apply them as arguments.

http://api.jquery.com/jQuery.when/

http://api.jquery.com/Deferred.then/



来源:https://stackoverflow.com/questions/8953620/jquerys-getscript-including-files-into-the-main-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!