javascript – 动态创建脚本:readyState从不“完成”

前端之家收集整理的这篇文章主要介绍了javascript – 动态创建脚本:readyState从不“完成”前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在脚本完全加载后,我正在尝试做一些事情. (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

代码

  1. var script = create the element and append to head...
  2.  
  3. // this works fine with FF/Chrome/...
  4. script.onload = function() {alert('script loading complete');}
  5. script.onerror = function() {alert('error loading script');}
  6.  
  7. // and for IE
  8. script.onreadystatechange = function() {
  9. // this will alert 1.loading 2.loaded
  10. alert(this.readyState);
  11.  
  12. // this never works
  13. if(this.readyState == 'complete') {alert('script loading complete');}
  14.  
  15. // this works with either a valid or INVALID url
  16. else if(this.readyState == 'loaded') {alert('script loaded');}
  17. };

在我的情况下,“完成”从不显示,即使一个网址无效,“加载”显示.所以没有办法判断一个脚本是否正确地加载到IE下.

我做错了吗?我怎么没有得到完整的状态?

UPDATE

好的,我只是读了一些文章,似乎readystate不是可靠的方式来检测脚本加载.

那么还有另一种方法呢?没有jQuery,而是纯JavaScript.

解决方法

根据您的评论,以下是如何使用XHR(XMLHttpRequest)动态添加脚本标签的原理图:
  1. var handleRequest = function( ) { //!! set up the handleRequest callback
  2.  
  3. if(this.status != undefined) {
  4.  
  5. /* do something with the status code here */
  6.  
  7. }
  8.  
  9. if(this.readyState == 4) {
  10.  
  11. var script = document.createElement("script") ;
  12. script.setAttribute("type","text/javascript") ;
  13. var text = document.createTextNode(this.responseText) ;
  14. script.appendChild(text) ;
  15.  
  16. var head = document.getElementsByTagName("head")[0] ;
  17. head.insertBefore(script,head.firstChild) ;
  18.  
  19. }
  20.  
  21. } ;
  22.  
  23. var request ; //!! supposing you have a way to get a working XHR Object
  24.  
  25. //.. set the XHR Object
  26.  
  27. request.open("GET",url,true) ;
  28. request.overrideMimeType("text/javascript") ;
  29. request.onreadystatechange = handleRequest ;
  30. request.send(null) ;

请记住,这只是给你一个我的意思的想法.一个工作的例子将是从jQuery源代码来更详细的判断.

链接

> W3 documentation for XMLHttpRequest
> MDN documentation for XMLHttpRequest
> MSDN documentation for XMLHttpRequest

猜你在找的JavaScript相关文章