function loadScript(url, callback) {var script = document.createElement_x_x('script');script.type = "text/javascript";if (script.readyState) {//IEscript.onreadystatechange = function () {if (script.readyState == 'loaded' || script.readyState == 'complete') {script.onreadystatechange = null;callback();}};}else{//其餘瀏覽器script.onload=function(){callback();}};script.scr=url;document.getElementsByTagName('head')[0].a(script);};loadScript('file.js',function(){console.log('file.js is loaded')});
loadScript('file.js',function(){loadScript('file2.js',function(){loadScript('file3.js',function(){console.log('all is load')})})});複製代碼
XMLHttpRequest腳本注入(大型web不推薦)
javascript
var xhr=new XMLHttpRequest();xhr.open('get','file.js',true);xhr.onreadystatechange=function(){if(xhr.readyState==4){if(xhr.status>=200&&xhr.status<<span style="color: #b5cea8;">300||xhr.status==304){var script=document.createElement_x_x('script');script.type='text/javascript';script.text='xhr.responseText';document.body.a(script)}}};xhr.send(null);複製代碼