本文實(shí)例講述了jQuery實(shí)現(xiàn)動(dòng)態(tài)加載(按需加載)javascript文件的方法。分享給大家供大家參考,具體如下:
為了提高網(wǎng)頁程序的性能,在很多情況下javascript 是按需加載,而不是全部寫在 <head>里面。利用jQuery可以很方便的實(shí)現(xiàn)按需加載js.
$("#load").click(function(){ $.getScript('helloworld.js', function() { $("#content").html('js 加載成功!'); });});
當(dāng)id為“l(fā)oad" 的按鈕被點(diǎn)擊之后,將會(huì)動(dòng)態(tài)加載 helloword.js , 然后就可以執(zhí)行里面的方法。
<html><head><script type="text/javascript" src="jquery-1.7.2.min.js"></script></head><body> <h1>利用 jQuery 動(dòng)態(tài)加載 js</h1><div id="content"></div><br/><button id="load">Load JavaScript</button><button id="sayHello">Say Hello</button><script type="text/javascript">$("#load").click(function(){ $.getScript('js-example/helloworld.js', function() { $("#content").html(' Javascript is loaded successful! sayHello() function is loaded! '); });});$("#sayHello").click(function(){ sayHello();});</script></body></html>
其中 helloworld.js 的代碼如下:
function sayHello(){ alert("Hello ~我是動(dòng)態(tài)加載的!");}
更多關(guān)于jQuery相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《jQuery頁面元素操作技巧匯總》、《jQuery常見事件用法與技巧總結(jié)》、《jQuery常用插件及用法總結(jié)》、《jQuery擴(kuò)展技巧總結(jié)》及《jquery選擇器用法總結(jié)》
希望本文所述對(duì)大家jQuery程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注