Javascript:“取消”动态脚本标签? [英] Javascript: "Cancelling" a dynamic script tag?
问题描述
我使用动态脚本标签从外部域请求javascript。有时请求需要太长时间如果请求太长,可以停止请求或超时吗?
我不想使用xmlhttprequest,因为我想避免使用服务器端代理。
谢谢!
说了不同的方式添加一个脚本是动态的,这样做的一个方法是在DOM准备就绪时向文档的正文添加一个< script>
节点,然后删除它很长的加载..
< html>
< head>
< title> bla< / title>
< script type =text / javascript>
函数init(){
var max_time = 2000 //以毫秒为单位
g_script_url =http://yoursite.net/script.js;
var script = document.createElement(script);
script.setAttribute(src,script_url);
script.setAttribute(type,text / javascript);
document.body.appendChild(script);
g_timeout = setTimeout(function(){
var scripts = document.getElementsByTagName(script);
for(var i = 0; i< scripts.length; i ++){
if(scripts [i] .src == script_url){
document.body.removeChild(scripts [i]);
}
}
},MAX_TIME);
}
window.addEventListener(DOMContentLoaded,init,false);
< / script>
< / head>
< body> bla bla [...]< / body>
< / html>
然后您可以添加一条指令来清除动态加载脚本末尾的超时: p>
/ * http://yoursite.net/script.js代码的结尾* /
clearTimout(g_timeout);
注意:
如果您希望跨平台解决方案使用Jquery的方法 document.addEventListener在IE中不起作用$(document).ready 或看看没有JQuery的文档就绪等价a>
I use dynamic script tags to request javascript from external domains. Sometimes the request takes too long; is it possible to stop the request or timeout if the requests takes too long?
I do not want to use xmlhttprequest because I'd like to avoid having to use a server side proxy.
Thanks!
Having said that there are different ways of adding a script dynamically, a way of doing this is by appending a <script>
node to the document's body when the DOM is ready, and then removing it if it takes to long to load..
<html>
<head>
<title>bla</title>
<script type="text/javascript">
function init(){
var max_time = 2000 //in milliseconds
g_script_url = "http://yoursite.net/script.js";
var script = document.createElement("script");
script.setAttribute("src",script_url);
script.setAttribute("type","text/javascript");
document.body.appendChild(script);
g_timeout=setTimeout(function(){
var scripts = document.getElementsByTagName("script");
for (var i=0; i < scripts.length; i++ ){
if (scripts[i].src == script_url){
document.body.removeChild(scripts[i]);
}
}
},max_time);
}
window.addEventListener("DOMContentLoaded", init, false);
</script>
</head>
<body>bla bla [...]</body>
</html>
Then you can add an instruction to clear the timeout at the end of the dynamically loaded script:
/* end of http://yoursite.net/script.js's code */
clearTimout(g_timeout);
NOTE:
document.addEventListener does not work in IE, if you want a cross platform solution use Jquery's method $(document).ready or have a look at Document ready equivalent without JQuery
这篇关于Javascript:“取消”动态脚本标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!