Loading remote JavaScript file in a page

大兔子大兔子 提交于 2020-02-28 07:06:14

问题


I've a simple page in which in the head I load several remote JavaScript files (I need them and can't have a local copy).

The scripts I load are similar to these:

<script type="text/javascript" src="http://mymachine/donald/script1.js"></script>
<script type="text/javascript" src="http://mymachine/donald/script2.js"></script>

In the first load of the page I got several error messages regarding objects that are related to these two scripts. So I think the page gets rendered BEFORE the scripts are downloaded and executed. If I try to reload the same page (with the cache loaded with the scripts) I don't get any errors.

However if I try to download each file two times, I don't get any error even if the cache of the browser is clean. I think it is a bad approach but I don't know any alternative.

Is there a tag that permits me to stop the rendering of the page unless the scripts are downloaded? Or an option of the browser? (I don't like this alternative but it could be only one). I need to support only Internet Explorer 7.

I have partially solved using a double loading of the js similar to this one:

but it is correct ?

<script type="text/javascript" src="http://mymachine/donald/script1.js"></script>
<script type="text/javascript" src="http://mymachine/donald/script1.js"></script>
<script type="text/javascript" src="http://mymachine/donald/script2.js"></script>
<script type="text/javascript" src="http://mymachine/donald/script2.js"></script>

the libraries are not dependant to each other. In fact if load alternatevly script1 and script2 the errors remains.


回答1:


That’s odd, I thought <script> tags in the <head> did block the page until they got downloaded.

Are they the first scripts in your <head> section? They’ll need to at least come before any JavaScript that relies on them.




回答2:


You should try pushing these tags very low on the page just before the </body>. If you only need to support IE7 this may solve the problem you are having.




回答3:


if your are executing the scripts from these files - wait for the load event of the document ...



来源:https://stackoverflow.com/questions/2231952/loading-remote-javascript-file-in-a-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!