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

Detailed explanation of how to load external css files in jQuery

伊谢尔伦
Release: 2017-07-21 09:30:30
Original
1897 people have browsed it

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");
Copy after login

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"
});
Copy after login

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);
}
Copy after login

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;]);
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template