JQuery implements the dynamic loading of css files, while jquery dynamically loads css files.
Sometimes we may need to use jQuery to load an external css file, for example, when switching the page layout. The idea is to create a link element and add it to the tag. Next, let's take a look at how to implement it using jQuery.
Below is my favorite writing method:
$("<link>").attr({ rel: "stylesheet",type: "text/css",href: "site.css"}).appendTo("head");
Some friends may use the following method, but the form is slightly different (append appendTo). The principle is 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 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);}
For web interaction, we can use jQuery or javascript to introduce a css file. Otherwise, we recommend that you use the original method.
Next I will introduce an instance that can load 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 + ">") ;}}); // usage $. includePath = 'HTTP: // hi. xxx/javascript/'; $. include (['json2. js', 'jquery. tree. js', 'jquery.tree.css ']);
A complete instance
Index.html
<!-- Created by Barrett at RRPowered.com --><!-- File name index.html -->