Dynamically add a CSS stylesheet to an HTML page with JavaScript/jQuery
This post will discuss how to dynamically add a CSS stylesheet to an HTML page using JavaScript and jQuery.
1. Using jQuery
If you work with jQuery, you may use the .appendTo() method to append a stylesheet at the end of the <head> element of the current document. Here’s how to do it:
|
1 2 3 4 5 6 7 |
// dynamically add bootstrap library var stylesheet = $("<link>", { rel: "stylesheet", type: "text/css", href: "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" }); stylesheet.appendTo("head"); |
Here’s alternate version using .append() method:
|
1 2 3 |
// dynamically add bootstrap library $('head').append('<link rel="stylesheet" type="text/css" \ href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />'); |
With the $.ajax() method, you can load the CSS from the server and enclose the content within the <style> tags, and finally append it at the end of the <head> element of the current document. The following code demonstrates this by dynamically loading the bootstrap library.
|
1 2 3 4 5 6 7 |
// dynamically add bootstrap library $.ajax({ url: "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css", success: function(data) { $("<style>").appendTo("head").html(data); } }) |
Here’s alternate version using .load() method:
|
1 2 3 |
// dynamically add bootstrap library $('<style>').load("https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css") .appendTo("head"); |
2. Using JavaScript
In vanilla JavaScript, you can use the native createElement() method to create a stylesheet and the appendChild() method to append the stylesheet at the end of the <head> element of the current document. Here’s how we can do it:
|
1 2 3 4 5 6 7 8 |
// dynamically add bootstrap library var link = document.createElement('link'); link.rel = "stylesheet"; link.type = "text/css"; link.href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"; document.head.appendChild(link); |
Alternatively, you can play around with the innerHTML property of Document.head.
|
1 2 3 4 5 |
// dynamically add bootstrap library var html = '<link rel="stylesheet" type="text/css" \ href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />'; document.head.innerHTML += html; |
That’s all about dynamically adding a CSS stylesheet to an HTML page using JavaScript and jQuery.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)