动态加载JavaScript文件无法按预期工作

时间:2013-08-20 14:37:48

标签: javascript performance settimeout

我正在动态加载javascript文件以加快页面的性能。代码是

 <head>  
 <script type="text/javascript">
     function includeJS(){
     var scriptElement = document.createElement('script');
     scriptElement.type = "text/javascript";
     scriptElement.src = "script/TestScript.js";
     document.getElementsByTagName('head')[0].appendChild(scriptElement);
     testFunction();
     }
 </script>
 </head>

testFunction()存在于TestScript.js中。因为JavaScript文件未完全加载,所以它会抛出'testFunction()未定义'之类的错误。所以我尝试使用setTimeout函数来修复它。代码是

setTimeOut('testFunction()',1000);

现在工作正常。但我无法将延迟时间1000放在服务器中,因为JavaScript文件加载取决于Internet速度和文件大小。那么有没有其他方法来解决它。

0 个答案:

没有答案