Home  >  Article  >  Web Front-end  >  Detailed explanation of how to load external css files in jQuery

Detailed explanation of how to load external css files in jQuery

伊谢尔伦
伊谢尔伦Original
2017-07-21 09:30:301801browse

Sometimes we may need to use jQuery to load an external css file, such as when switching page layouts. The idea is to create a link element and add it to the tag. Let's first see how to use jQuery to achieve it.


$("<link>")
.attr({ rel: "stylesheet",
type: "text/css",
href: "site.css"
})
.appendTo("head");

Some friends may use the writing method below, but the form is slightly different (append appendTo), but the principle is still the same.


$("head").append("<link>");
css = $("head").children(":last");
css.attr({
rel: "stylesheet",
type: "text/css",
href: "/Content/Site.css"
});

Finally, some friends may want to use it directly in javascript, the method is as follows:


function addCSS() {
var link = document.createElement(&#39;link&#39;);
link.type = &#39;text/css&#39;;
link.rel = &#39;stylesheet&#39;;
link.href = &#39;/Content/Site.css&#39;;
document.getElementsByTagName("head")[0].appendChild(link);
}

If so During web interaction, we can use the above method to introduce a css file through jQuery or javascript, otherwise it is recommended to use the original method.

The following also introduces an example of loading js and css

The code is as follows


$.extend({
includePath: &#39;&#39;,
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 + ">");
}
}
});
//使用方法
$.includePath = &#39;http://hi.xxx/javascript/&#39;; 
$.include([&#39;json2.js&#39;, &#39;jquery.tree.js&#39;, &#39;jquery.tree.css&#39;]);

The above is the detailed content of Detailed explanation of how to load external css files in jQuery. 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