jQuery動態載入js指令檔

來源:互聯網
上載者:User

標籤:

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指令檔

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.