@H_404_1@在脚本完全加载后,我正在尝试做一些事情. (IE8)
脚本我用于测试:http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js
和无效的一个:http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.minaaaaaaaa.js
代码…
var script = create the element and append to head... // this works fine with FF/Chrome/... script.onload = function() {alert('script loading complete');} script.onerror = function() {alert('error loading script');} // and for IE script.onreadystatechange = function() { // this will alert 1.loading 2.loaded alert(this.readyState); // this never works if(this.readyState == 'complete') {alert('script loading complete');} // this works with either a valid or INVALID url else if(this.readyState == 'loaded') {alert('script loaded');} };
在我的情况下,“完成”从不显示,即使一个网址无效,“加载”显示.所以没有办法判断一个脚本是否正确地加载到IE下.
我做错了吗?我怎么没有得到完整的状态?
UPDATE
好的,我只是读了一些文章,似乎readystate不是可靠的方式来检测脚本加载.
那么还有另一种方法呢?没有jQuery,而是纯JavaScript.
解决方法
根据您的评论,以下是如何使用XHR(XMLHttpRequest)动态添加脚本标签的原理图:
var handleRequest = function( ) { //!! set up the handleRequest callback if(this.status != undefined) { /* do something with the status code here */ } if(this.readyState == 4) { var script = document.createElement("script") ; script.setAttribute("type","text/javascript") ; var text = document.createTextNode(this.responseText) ; script.appendChild(text) ; var head = document.getElementsByTagName("head")[0] ; head.insertBefore(script,head.firstChild) ; } } ; var request ; //!! supposing you have a way to get a working XHR Object //.. set the XHR Object request.open("GET",url,true) ; request.overrideMimeType("text/javascript") ; request.onreadystatechange = handleRequest ; request.send(null) ;
请记住,这只是给你一个我的意思的想法.一个工作的例子将是从jQuery源代码来更详细的判断.
链接:
> W3 documentation for XMLHttpRequest
> MDN documentation for XMLHttpRequest
> MSDN documentation for XMLHttpRequest