实现异步加载js文件及加载完成后回调
兼容IE特有的,火狐、Chrome等一些现代浏览器,加载JS的代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
function loadJS(src, callback){ var script = document.createElement('script'); var head = document.getElementsByTagName('head')[0]; var loaded; script.src = src; if(typeof callback === 'function'){ script.onload = script.onreadystatechange = function(){ if(!loaded && (!script.readyState || /loaded|complete/.test(script.readyState))){ script.onload = script.onreadystatechange = null; loaded = true; callback(); } } } head.appendChild(script); } |