Blackbing Playground

動態載入Javascript

jQuery中動態載入Javascript的方式寫得很不錯,修改了一下把他拿出來用。但若要動態載入CSS就沒辦法使用onload的callback,可能還是要使用setInterval來檢查是否load到頁面上。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var 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);
};