javascript之js加载理解
文档加载事件意义,看下面例子
document.addEventListener('DOMContentLoaded', function() { }) $(document).ready(function() { }) //文档解析完(只解析domTree,不加载资源) window.onload = function() { } //文档加载完(包括img的src,所有资源加载完)
异步加载js
1.defer异步加载,但是要到dom文档全部解析完才会被执行。只有IE能用,也可以将代码写到内部
2.async异步加载,加载完就执行,async只能加载外部脚本,不能把js写在script标签里面
1.2执行时不阻塞页面
3.创建script,插入到DOM中,加载完毕后callBack(推荐)
封装异步加载script
function loadScript(url, callback) { var script = document.createElement('script') script.type = 'text/javascript' if(script.readyState) { script.onreadystatechange = function() { //IE if(script.readyState == 'complete' || script.readyState == 'loaded') { callback() } } }else { script.onload = function() { //safari chrome firefox opera callback() } } script.src = url document.body.appendChild(script) }
end !!!