简体   繁体   English

将数组转换为 function,使用 jquery 制作 javascript 加载器

[英]turn array into function, making a javascript loader with jquery

how can we make a function from arrays like我们如何从 arrays 中制作 function

$.loader({
    js: [
        ['1.js','3.js','2.js'], 
        ['4.js'], 
        ['5.js'] 
    ]
}); 

into something that does做某事

$.when(
    $.getScript("1.js"),
    $.getScript('3.js'),
    $.getScript('2.js'))
    .then(
        function(){
            $.getScript('4.js').then(function(){
                $.getScript('5.js');
            })
        });

heres what currently im working on这是我目前正在做的事情

loader: function(arg){
    var js = arg;
    var phase = 0;
    for (var i = 0; i < o.length; i++) {
        console.log(o[i]);
        $.each(o[i], function(key,src) {
            //append javascript
        });
    };
}

在此处输入图像描述

the problem is i dont know where to start.问题是我不知道从哪里开始。 heres what i have in mind这是我的想法

  1. i divide them into phases.我把它们分成几个阶段。
  2. set phase 0, it will run the fist array but how can i do it?设置阶段 0,它将运行第一个数组,但我该怎么做? $.getScript(src) for each src dosent stack.每个 src 剂量堆栈的$.getScript(src) or chain.或链。 maybe put it one var sting?也许把它一个 var 刺痛? like string + = $.getScript(src).string + = $.getScript(src). so it will be like $.getScript("1.js").getScript("3.js").getScript("2.js") until there is arrays of string which is 3 in this example.所以它会像$.getScript("1.js").getScript("3.js").getScript("2.js")直到有 arrays 的字符串,在这个例子中是 3。 then do something like append $.when( infront of the string then at the back of the string we put .then(function(){ until it finish then somehow closed the string.然后做类似 append $.when(在字符串前面然后在字符串后面我们放.then(function(){直到它完成然后以某种方式关闭字符串。
  3. ok i dont know ( and here goes the post at stackoverflow )好的,我不知道(这里是stackoverflow的帖子)
function lScripts(startAt){
for (var i = startAt; i < js.length; i++) {    
    if (js[i].constructor == Array){
        for (var j = 0; j < js[i].length; j++) {
            if(j==js[i].length){
                $.getScript('js[i][j]',function(){
                    lScripts(startAt+1);
                });
            }else{
                $.getScript('js[i][j]');
            }

        }

    }else{
         $.getScript('js[i]',function(){
            lScripts(startAt+1);
         });

    }
}
}

lScripts(0);

Just to be clear, are you talking about writing a solution yourself that loads up a bunch of scripts?为了清楚起见,您是在谈论自己编写一个加载一堆脚本的解决方案吗? If so, dont do it yourself.如果是这样,请不要自己做。 Stand on someone else's shoulders.站在别人的肩膀上。

RequireJS already does what you're asking. RequireJS 已经完成了您的要求。 http://requirejs.org/ http://requirejs.org/

It even has documentation for use with jQuery.它甚至还有用于 jQuery 的文档。 http://requirejs.org/docs/jquery.html http://requirejs.org/docs/jquery.html

Someone else already did the hard work and wrote and tested a good product.其他人已经做了艰苦的工作,编写并测试了一个好的产品。 Save yourself time and stress.节省自己的时间和压力。

I hope this is what you mean: http://jsfiddle.net/pimvdb/hdN3Q/1/ .我希望这就是您的意思: http://jsfiddle.net/pimvdb/hdN3Q/1/

(function($) {
    function load(files, index) {
        var arr = [];

        // fill arr with getScript requests (fake here)
        for(var i = 0; i < files[index].length; i++) {
            arr.push(console.log(files[index][i]));
        }

        // call $.when with arr as array of arguments (using apply)
        $.when.apply(null, arr).then(function() {
            if(index < files.length - 1) {
                // if we have to move to the next chunk,
                // load that next one
                setTimeout(function() {
                    // timeout is to show they get processed in chunks
                    load(files, index + 1);
                }, 1000);
            }
        });
    }

    $.loader = function(obj) {
        load(obj.js, 0);
    }
})(jQuery);

$.loader({
    js: [
        ['1.js','3.js','2.js'], 
        ['4.js'], 
        ['5.js'] 
    ]
});

.apply essentially does the same thing as calling a function. .apply本质上与调用 function 的作用相同。 However, because the amount of arguments to $.when differs depending on the input, you can't just call $.when(...) because you don't have a fixed number of arguments.但是,由于 arguments 到$.when .when 的数量因输入而异,因此您不能只调用$.when(...) ,因为您没有固定数量的 arguments。 The way to call a function with a variable amount of arguments is using .apply .使用可变数量的 arguments 调用 function 的方法是使用.apply It works like this:它是这样工作的:

someFunction(1, 2, 3);

is equal to:等于:

someFunction.apply(null, [1, 2, 3]);

(The null refers to the execution context which is out of scope here.) The great thing about this is that you can build an array of any size. (这里的null指的是 scope 之外的执行上下文。)这样做的好处是您可以构建任意大小的数组。 So you can call the function with any variable amount of arguments this way.因此,您可以通过这种方式使用任意可变数量的 arguments 调用 function。

In the load function, arr gets filled with getScript functions, and it works the same way:load function 中, arrgetScript函数填充,它的工作方式相同:

var arr = [getScript('file1'), getScript('file2')];
$.when.apply(null, arr);

is equal to:等于:

$.when(getScript('file1'), getScript('file2'));

In load , we fill arr with the files of a chunk, eg in your case the first chunk is 1.js , 3.js and 2.js .load中,我们用一个块的文件填充arr ,例如,在您的情况下,第一个块是1.js3.js2.js This is done using a for loop but the array you will end up with you can just pass to .apply .这是使用for循环完成的,但最终得到的数组可以传递给.apply


When all files are loaded, .then is called.加载所有文件后,将调用.then The function we pass there should load the next chunk, but only if there is a next chunk.我们在那里传递的 function 应该加载下一个块,但前提存在下一个块。 If there are 3 chunks, it should go to the next one when index is 0 or 1 .如果有 3 个块,当index01时,它应该 go 到下一个块。 When chunk 2 has finished, there is no next chunk so it should not continue to the next one as there isn't a next one.当块2完成时,没有下一个块,所以它不应该继续到下一个,因为没有下一个。

So we need this if clause:所以我们需要这个if子句:

if(index < files.length - 1) {

Say files.length is 3 .files.length3 Then this if conditional will only pass when index is 0 or 1 , which is what we want.那么这个if条件只会在index01时通过,这就是我们想要的。

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

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