Load a Javascript file, but cancel if it takes too long?

别来无恙 提交于 2019-12-23 04:23:17

问题


Anyone have a good way to load a JS file but cancel loading it if it takes too long?

I'm thinking something like this, hypothetically:

<script type="text/javascript" cancel_after="2000" src="myfile.js"></script>

The script is code that needs to get loaded in the head, because it replaces elements on the page, and so the browser needs to block while loading it. But in case the server takes too long to respond, I'd like to be able to have the browser proceed without loading the script.


回答1:


Use a preloader. I personally prefer yepnope, where you can easily set a timeout using yepnope.errorTimeout = 2000

Check the linked page for a rather complete documentation of yepnope.




回答2:


You can load the JavaScript using an ajax call then use eval to run it at your leisure. In jQuery it would look something like this.

$.ajax('test.js', {timeout: 100 /* milliseconds */, success: function(result) {
  eval(result);
});

It aint pretty, and the code in the included JavaScript may need to be coded differently, but this might do it for you.




回答3:


You can put <script></script> after <body></body> or load it via JS (document.onload)

If you really want to cancel loading, then think about using XMLHTTPRequest and abort() function



来源:https://stackoverflow.com/questions/5642270/load-a-javascript-file-but-cancel-if-it-takes-too-long

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