Jquery dynamically loads the js and CSS file method of of

  • 2020-03-30 04:05:07
  • OfStack

Let's start with jquery's built-in getSrcript files

methods

$. GetScript (url, callback)

The instance


var testVar = 'New JS loaded!';
alert(testVar); function newFun(dynParam) {
alert('You just passed '+dynParam+ ' as parameter.');
}

Dynamic invocation 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"');//This function is inside new.js and runs when you click click }); }); }); </script> </head> <body> <button type="button" id="loadButton">Load</button>

The above can only dynamically load js code, but can not load CSS, later I wrote a load js and CSS procedures.

The following code


$.extend({
includePath: '',
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(['hdivbox.js','pop_win.css']);


Related articles: