Home  >  Article  >  Web Front-end  >  How jquery dynamically loads js/css files

How jquery dynamically loads js/css files

php中世界最好的语言
php中世界最好的语言Original
2018-04-23 14:41:111119browse

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(&#39;.&#39;);
var ext = att[att.length - 1].toLowerCase();
var isCSS = ext == "css";
var tag = isCSS ? "link" : "script";
var attr = isCSS ? " type=&#39;text/css&#39; rel=&#39;stylesheet&#39; " : " language=&#39;javascript&#39; type=&#39;text/javascript&#39; ";
var link = (isCSS ? "href" : "src") + "=&#39;" + $.includePath + name + "&#39;";
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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn