2017-08-31 47 views
0

我正在加载从服务器返回的一些脚本...有些脚本中定义了对象...将脚本附加到主体并尝试创建一个新的对象考虑的脚本,因此对象在页面加载定义...这是不是这样的,因为这是投掷找不到对象错误......这里的代码看起来...对象未定义...动态加载脚本并创建其中定义的对象引发错误

for(var i=0; i < paths; i++){ 
    var script = document.createElement('script'); 
    script.type='text/javascript'; 
    script.src=paths[i].src; 
    document.body.appendChild(script); 
} 
var new_obj = new object_name(a, b, c); // object_name not found 

我可以看到该脚本已成功添加到元素选项卡中的正文。

我试过在页面主体的末尾手动加载脚本及其工作这种方式而不是当我加入动态文件...请告诉我怎么回事错了....

+0

你试过延缓'新OBJECT_NAME()'直到'script.onload'事件发生后? – nnnnnn

+0

不......没有尝试......在for循环中加载了几个文件......我应该如何使用这个特定脚本的onload? –

+0

有没有什么办法可以在循环中使用onload来延迟执行? –

回答

0

您可以将async属性设置为false(以便按顺序同步加载脚本)并执行onload事件来验证脚本是否已加载。下面的代码显示了实现。我在实现中可能是错误的,或者可能有更好的方法来加载基于数组的脚本(循环)并检查所有加载的文件。

<script> 
     window.onload = function() { LoadFunctions(); } 
     var paths = ["test.js", "test2.js"]; 

     function LoadFunctions() { 
      for(var i=0; i < paths.length; i++){ 
       var script = document.createElement('script'); 
       script.type='text/javascript'; 
       script.src=paths[i]; 
       script.async = false; 
       script.onload = function() { callFunctions(); } 
       document.head.appendChild(script); 
      } 
     } 

     function callFunctions(){ 
      if (typeof test1 != "undefined") test1(); //Check for function in test.js whether loaded or not then execute it 
      if (typeof test2 != "undefined") test2(); //Check for function in test2.js whether loaded or not then execute it 
     } 
</script> 

test.js

function test1(){ 
    alert("Alert from test.js"); 
} 

test2.js

function test2(){ 
    alert("Alert from test2.js"); 
}