This example describes the way JavaScript dynamically creates link tags into the head. Share to everyone for your reference. The specific analysis is as follows:
I believe there are a lot of front-end friends who need to dynamically create style sheet labels--link labels with JavaScript. Here we say how to dynamically create a link label in a browser.
Create a link label with JQuery
If you like to use jquery in your development, then using jquery to create the link tag should be like this:
Copy Code code as follows:
var cssurl = '/style.css ',
Linktag = $ (' <link href= ' + cssurl + ' "rel=" stylesheet "type=" Text/css "media=" ' + "(Media | | "All") + ' "charset=" ' + CharSet | | "Utf-8" + ' "/>");
See clearly that the link tag is dynamically added to the head
$ ($ (' head ') [0]). Append (Linktag);
Create a link label with native JavaScript
If you like pure natural JavaScript, you need to write this:
Copy Code code as follows:
var head = document.getElementsByTagName (' head ') [0],
Cssurl = '/style.css ',
Linktag = document.createelement (' link ');
linktag.id = ' Dynamic-style ';
Linktag.href = Cssurl;
Linktag.setattribute (' rel ', ' stylesheet ');
Linktag.setattribute (' media ', ' all ');
Linktag.setattribute (' type ', ' text/css ');
Head.appendchild (Linktag);
IE Method createStyleSheet
IE createStyleSheet method is also very convenient.
Copy Code code as follows:
var head = document.getElementsByTagName (' head ') [0],
Cssurl = ' Themes/bluenight/style.css ',
Document.createstylesheet the link tag has been added to the head, how to say, it is very convenient
Linktag = Document.createstylesheet (Cssurl);
createStyleSheet ([sURL] [, Iindex]) method accepts two parameters, sURL is the URL path of the CSS file. Iindex is an optional parameter that refers to the index position of the inserted link in the page stylesheets collection, which defaults to adding the newly created style at the end.
A complete solution
Basically all introduced, to see the Complete solution bar:
Copy Code code as follows:
function Createlink (Cssurl,lnkid,charset,media) {
var head = $ ("head") [0]),
Linktag = null;
if (!cssurl) {
return false;
}
Linktag = $ (' <link href= ' + cssurl + ' "rel=" stylesheet "type=" Text/css "media=" ' + "(Media | | "All") + ' "charset=" ' + CharSet | | "Utf-8" + ' "/>");
Head.append (Linktag);
}
function Createlink (Cssurl,lnkid,charset,media) {
var head = document.getElementsByTagName (' head ') [0],
Linktag = null;
if (!cssurl) {
return false;
}
Linktag = document.createelement (' link ');
Linktag.setattribute (' id ', Lnkid | | ' Dynamic-style '));
Linktag.setattribute (' rel ', ' stylesheet ');
Linktag.setattribute (' CharSet '), (CharSet | | ' Utf-8 '));
Linktag.setattribute (' Media ', (media| | ') All));
Linktag.setattribute (' type ', ' text/css ');
Linktag.href = Cssurl;
Head.appendchild (Linktag);
}
I hope this article will help you with your JavaScript programming.