Last active
June 21, 2016 02:08
-
-
Save xubo-bj/568b098c12c870bebb0104c5b8b93ffd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 如果 不放在 window.onload里, 在 onload之前执行。 | |
| // 如果放在 setTimeout里,可以在onload之后执行。 | |
| //后续代码依赖loadScript加载代码时,将后续代码放在callback中 | |
| //多数浏览器,返回的代码会立即执行(Firefox、Opera,会等待此前所有动态节点执行完毕) | |
| //个人理解,动态节点:通过loadScript 加载的就算里一个动态节点。 | |
| function loadScript(url, callback) { | |
| var script = document.createElement("Script"); | |
| script.type = "text/javascript"; | |
| //IE 验证脚本是否下载完成 | |
| if (script.readyState) { | |
| script.onreadystatechange = function() { | |
| //readyState属性有5种取值 | |
| //uninitialized:初始状态 | |
| //loading:开始下载 | |
| //interactive:数据完成下载但尚不可用 | |
| //complete:数据已经准备就绪 | |
| //实际使用时,readyState的值并不像我们预想的那样有规律,实践发现使用readyState | |
| //最靠谱的方式是同时检查以下2个状态,只要其中1个触发,就认为脚本下载完成。 | |
| if (script.readyState == "loaded" || script.readyState == "complete") { | |
| //移除事件处理器,确保事件不会处理2次 | |
| script.onreadystatechange = null; | |
| callback(); | |
| } | |
| }; | |
| } | |
| //其他浏览器 | |
| else { | |
| script.onload = function() { | |
| callback(); | |
| }; | |
| } | |
| script.src = url; | |
| //把新建的<Script>添加到<head>里比添加到<body>里更保险。 | |
| document.getElementsByTagName("head")[0].appendChild(script); | |
| } | |
| //动态加载多个JS文件 | |
| //优先加载Common.js,等待Common.js加载完毕后加载Costom.js | |
| //不同浏览器的执行顺序不同 | |
| //Firefox、Opera能够保证按照你脚本的加载顺序来执行 | |
| //其他浏览器会按照从服务端返回的顺序执行代码,因此使用嵌套的方法保证调用顺序 | |
| loadScript("Common.js", function() { | |
| loadScript("Costom.js", function() { | |
| alert("all load"); | |
| }); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment