動態載入Javascript 發表於 2009-01-15 | jQuery中動態載入Javascript的方式寫得很不錯,修改了一下把他拿出來用。但若要動態載入CSS就沒辦法使用onload的callback,可能還是要使用setInterval來檢查是否load到頁面上。 1234567891011121314151617181920var getScript = function(url, callback){ var script; script = document.createElement("script"); script.setAttribute('language', 'javascript'); script.setAttribute('type', 'text/javascript'); script.setAttribute('src', url); var done = false; script.onload = script.onreadystatechange = function(){ if ( !done && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete") ) { done = true; if(typeof callback === 'function') callback(); if(this.tagName.toLowerCase() == 'script') document.getElementsByTagName('head')[0].removeChild(this); } }; var head = document.getElementsByTagName('head')[0]; head.appendChild(script);};