標籤:
jQuery getScript()方法載入JavaScript
jQuery.getScript("/path/to/myscript.js", function(data, status, jqxhr) { /* 做一些載入完成後需要執行的事情 */ });
jQuery.getScript("/path/to/myscript.js") .done(function() { /* 耶,沒有問題,這裡可以幹點什麼 */ }) .fail(function() { /* 靠,馬上執行挽救操作 */});
jquery getScript動態載入JS方法改進
<!DOCTYPE html > <html> <head> <meta charset="utf-8"> <title></title> <script src="jquery-1.7.2.min.js" type="text/javascript"></script> <script type="text/javascript"> //定義一個全域script的標記數組,用來標記是否某個script已經下載到本地 var scriptsArray = new Array(); $.cachedScript = function (url, options) { //迴圈script標記數組 for (var s in scriptsArray) { //console.log(scriptsArray[s]); //如果某個數組已經下載到了本地 if (scriptsArray[s]==url) { return { //則返回一個對象字面量,其中的done之所以叫做done是為了與下面$.ajax中的done相對應 done: function (method) { if (typeof method == ‘function‘){ //如果傳入參數為一個方法 method(); } } }; } } //這裡是jquery官方提供類似getScript實現的方法,也就是說getScript其實也就是對ajax方法的一個拓展 options = $.extend(options || {}, { dataType: "script", url: url, cache:true //其實現在這緩衝加與不加沒多大區別 }); scriptsArray.push(url); //將url地址放入script標記數組中 return $.ajax(options); }; $(function () { $(‘#btn‘).bind(‘click‘, function () { $.cachedScript(‘t1.js‘).done(function () { alertMe(); }); }); $(‘#btn2‘).bind(‘click‘, function () { $.getScript(‘t1.js‘).done(function () { alertMe(); }); }); }); </script> </head> <body> <button id="btn">自訂的緩衝方法</button> <br /> <button id="btn2">getScript</button> </body> </html>
t1.js中代碼也就是一個函數
function alertMe() { alert(‘clicked me‘); }
jQuery動態載入js指令檔