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('link'); link.type = 'text/css'; link.rel = 'stylesheet'; link.href = '/Content/Site.css'; 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: '', 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 + ">"); } } }); //使用方法 $.includePath = 'http://hi.xxx/javascript/'; $.include(['json2.js', 'jquery.tree.js', 'jquery.tree.css']);
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!