Home > Article > Web Front-end > How jquery dynamically loads js/css files
jqueryThe built-in getSrcript file can only dynamically load js code, but cannot load css. Later, I wrote a program that can load js and css.
Let’s first look at jquery itself The getSrcript file with
Method
$.getScript(url,callback)
Instance
var testVar = 'New JS loaded!'; alert(testVar); function newFun(dynParam) { alert('You just passed '+dynParam+ ' as parameter.'); }
Dynamic call method
<script type="text/javascript" src="../jquery.js"></script> <script type="text/javascript"> $(function() { $('#loadButton').click(function(){ $.getScript('new.js',function(){ newFun('"Checking new script"');//这个函数是在new.js里面的,当点击click后运行这个函数 }); }); }); </script> </head> <body> <button type="button" id="loadButton">Load</button>
The above can only dynamically load js code, but cannot load css. Later, I wrote a program that can load js and css.
$.extend({ include Path: '', include: function(file) { var files = typeof file == " string " ? [file] : file; for (var i = 0; i < files.length; i++) { var name = files[i].replace(/^s|s$/g, ""); var att = name.split('.'); var ext = att[att.length - 1].toLowerCase(); var isCSS = ext == "css"; var tag = isCSS ? "link" : "script"; var attr = isCSS ? " type='text/css' rel='stylesheet' " : " language='javascript' type='text/javascript' "; var link = (isCSS ? "href" : "src") + "='" + $.includePath + name + "'"; if ($(tag + "[" + link + "]").length == 0) document .write("<" + tag + attr + link + "></" + tag + ">"); } } }); $.include(['hpbox.js','pop_win.css']);
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to the php Chinese website Other related articles!
Recommended reading:
Jquery LigerUI detailed explanation of file upload steps
jquery dynamically loaded js file detailed explanation
The above is the detailed content of How jquery dynamically loads js/css files. For more information, please follow other related articles on the PHP Chinese website!