且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

jQuery的getScript加入 - 包括文件转换成主要适用范围?

更新时间:2023-12-04 22:59:10

那么首先,你只是叫装载机()强似功能:

  $(文件)。就绪(装载机);

将解决这个问题。

其次,您呼叫的的init 回调的时候了,而不是当加载的所有脚本。如果有很多的脚本,你需要使用的承诺:

  VAR脚本= ['/app/routers/myrouter.js'];
    对于(VAR I = 0; I< scripts.length;我++){
        脚本由[i] = $ .getScript(脚本[I]);
    }
    $ .when.apply($,脚本)。然后(INIT,函数(){
        一些脚本失败;
    });

以上使用的语法是 $时(promise1,promise2,...),那么(successCallback,failureCallback) - 。我们填补阵列的承诺和使用。适用将它们应用作为参数。

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

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

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());

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/