zoukankan      html  css  js  c++  java
  • 仅IE9/10/(Opera)同时支持script元素的onload和onreadystatechange事件

    如下

    <!DOCTYPE HTML>
    <html>
    	<head>
    		<meta charset="utf-8">
    		<title>IE9/10同时支持script元素的onload和onreadystatechange事件</title>
    		<script src="http://code.jquery.com/jquery.min.js" onload="alert(1)" onreadystatechange="alert(2)"></script>
    	</head>
    	<body>
    	</body>
    </html>
    

    结果:

    IE6/7/8 : 弹出2

    IE9/10 : 弹出2,1

    Firefox/Safari/Chrome/Opera : 弹出1

    测试结果可以看出,IE9后已经开始支持script的onload事件了。一直以来我们判断js文件是否已经加载完成就是用以上的两个事件。很久以前就知道IE中使用onreadystatechange事件,事件handler中使用readyState的值判断是否加载完成。其它浏览器使用onload事件。

    if (isIE) {
    	script.onreadystatechange = function() {
    		if (this.readyState == 'loaded' || this.readyState == 'complete') {
    			callback();
    		}
    	}
    } else {
    	script.onload = function() {
    		callback();
    	}
    }
    

      

    这种写法现在也没有问题。但如下写法可能会让的回调在IE9/10中执行两次

    script.onload = script.onreadystatechange = function(){
    	if(!this.readyState || this.readyState == "loaded" || this.readyState == "complete"){
    		callback();
    	}
    }
    

      

    这种写法的取巧之处在于onload和onreadystatechage都用同一个函数,Firefox/Safari/Chrome/Opera中不支持onreadystatechage事件,也没有readyState属性,所以 !this.readyState 是针对这些浏览器。readyState是针对IE浏览器,载入完毕的情况是loaded,缓存的情况下可能会出现readyState为complete。所以两个不能少。但由于IE9/10也已经支持onload事件了,会造成callback执行2次。

    注意:动态创建的script在Opera中是支持onreadystatechange事件的

    相关:

    http://www.w3.org/TR/html401/interact/scripts.html#h-18.2.1 

    http://www.w3.org/TR/html5/scripting-1.html#script

    https://developer.mozilla.org/En/HTML/Element/Script 

  • 相关阅读:
    算法第二章上机实践报告
    算法第一章作业
    第7章学习小结 不使用STL-map过实践题:QQ帐户的申请与登陆
    第6章学习小结
    HDU
    HDU 2089 不要62(数位DP)
    char-2
    chart-7
    chart-6
    char-8
  • 原文地址:https://www.cnblogs.com/snandy/p/2029537.html
Copyright © 2011-2022 走看看