简体   繁体   English

注册JavaScript文件和相关的内联代码

[英]Registering JavaScript files and dependent inline code

I have two arrays. 我有两个数组。

  1. A list of urls to JavaScript files that I am registering with $.getScript(url); 我使用$ .getScript(url)注册的JavaScript文件的URL列表;
  2. A list of inline JavaScript commands to register with $("html").append(inline) 要使用$(“html”)注册的内联JavaScript命令列表.adndnd(内联)

Any items in (2) may be dependant on any items in (1). (2)中的任何项目可能取决于(1)中的任何项目。 Meaning that I have to be sure that all items in (1) have finished loading before any of (2) are registered. 这意味着我必须确保(1)中的所有项目在注册任何(2)之前已完成加载。

I want to load all of (1) asynchronously... since it will be faster, but how do I ensure that all of these processes have finished before registering (2)? 我想异步加载所有(1)...因为它会更快,但如何在注册(2)之前确保所有这些进程都已完成?

I think this way it should work: 我认为这应该有效:

var scripts = [
  {"src": "script1", "loaded": false},
  {"src": "script2", "loaded": false},
  {"src": "script3", "loaded": false},
]
var commands = ["cmd1","cmd2","cmd3"];

for (var i = 0, l = scripts.length; i<l; i++){
  (function (script){
    $.ajax({
      url: script.src,
      dataType: 'script',
      success: function (){

        for (var k = scripts.length; k--;){
          if (scripts[k].src === script.src){
            scripts[k].loaded = true;
          }
        }

        var allReady = true;
        for (var k = scripts.length; k--;){
          if (!scripts[k].loaded){
            allReady = false;
          }
        }
        if (allReady){
          /*execute your inline commands*/
        }
      }
    });
  })(scripts[i]);
}

This should in my opinion be solvable via jQuery's callback capacity; 在我看来,这应该可以通过jQuery的回调容量来解决; see succinct usage descriptions here , hope this helps. 在这里查看简洁的用法说明,希望这会有所帮助。

EDIT: here's the actual code: 编辑:这是实际的代码:

$.extend({myFunc : function(someArg, callbackFnk){
// load files here
var data = 'test';

// now call function for inline loading
if(typeof callbackFnk == 'function'){
  callbackFnk.call(this, data);
}}});

$.myFunc(someArg, function(arg){ */here goes inline load*/ });

你可以在ajax调用的成功处理程序中添加(2)。

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

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