This article describes the method of dynamically creating link tags into the head of JavaScript. Share it for your reference. The specific analysis is as follows:
I believe that many front-end friends have encountered the need to use JavaScript to dynamically create stylesheet tags - link tags. Here we will talk about how to dynamically create link tags in the browser.
Create link tags with jQuery
If you like to use jQuery in development, then using jQuery to create link tags should look like this:
The code copy is as follows: var cssURL = '/style.css',
linkTag = $('<link href="' + cssURL + '" rel="stylesheet" type="text/css" media="' + (media || "all") + '" charset="'+ charset || "utf-8" +'" />');
// Please see clearly, dynamically add link tags to the head
$($('head')[0]).append(linkTag);
Create link tags using native JavaScript
If you like pure and natural JavaScript, you need to write it like this:
The code copy is 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's unique method createStyleSheet
The unique method of IE is also very convenient.
The code copy is as follows: var head = document.getElementsByTagName('head')[0],
cssURL = 'themes/BlueNight/style.css',
// document.createStyleSheet has added the link tag to the head. How to say it, it is quite convenient
linkTag = document.createStyleSheet(cssURL);
The createStyleSheet([sURL] [, iIndex]) method accepts two parameters, and the sURL is the URL path of the CSS file. iIndex is an optional parameter, which refers to the index position of the stylesheets collection inserted in the page. By default, the newly created style is added at the end.
Complete solution
Basically, all of them have been introduced, let’s take a look at the complete solution:
The code copy is 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 be helpful to everyone's JavaScript programming.