简体   繁体   English

加载Javascript文件,但是如果花费太长时间则取消?

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

Anyone have a good way to load a JS file but cancel loading it if it takes too long? 任何人都有加载JS文件的好方法,但是如果加载时间太长,可以取消加载它?

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. 但是,如果服务器响应时间太长,我希望能够在不加载脚本的情况下继续运行浏览器。

Use a preloader. 使用预加载器。 I personally prefer yepnope , where you can easily set a timeout using yepnope.errorTimeout = 2000 我个人更喜欢yepnope ,在这里您可以使用yepnope.errorTimeout = 2000轻松设置超时时间

Check the linked page for a rather complete documentation of yepnope. 在链接页面上查看有关yepnope的完整文档。

You can load the JavaScript using an ajax call then use eval to run it at your leisure. 您可以使用ajax调用加载JavaScript,然后使用eval随意运行它。 In jQuery it would look something like this. 在jQuery中,它看起来像这样。

$.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. 看起来还不错,并且所包含的JavaScript中的代码可能需要进行不同的编码,但这可能为您做到了。

You can put <script></script> after <body></body> or load it via JS ( document.onload ) 您可以将<script></script>放在<script></script> <body></body>或通过JS( document.onload )加载它

If you really want to cancel loading, then think about using XMLHTTPRequest and abort() function 如果您确实要取消加载,请考虑使用XMLHTTPRequestabort()函数

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

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