本文實例講述了jQuery實現動態加載(按需加載)javascript文件的方法。分享給大家供大家參考,具體如下:
為了提高網頁程序的性能,在很多情況下javascript 是按需加載,而不是全部寫在 <head>里面。利用jQuery可以很方便的實現按需加載js.
$("#load").click(function(){ $.getScript('helloworld.js', function() { $("#content").html('js 加載成功!'); });});
當id為“load" 的按鈕被點擊之后,將會動態加載 helloword.js , 然后就可以執行里面的方法。
<html><head><script type="text/javascript" src="jquery-1.7.2.min.js"></script></head><body> <h1>利用 jQuery 動態加載 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 ~我是動態加載的!");}
更多關于jQuery相關內容感興趣的讀者可查看本站專題:《jQuery頁面元素操作技巧匯總》、《jQuery常見事件用法與技巧總結》、《jQuery常用插件及用法總結》、《jQuery擴展技巧總結》及《jquery選擇器用法總結》
希望本文所述對大家jQuery程序設計有所幫助。
新聞熱點
疑難解答