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:

Edit in JSFiddle

 
Here’s alternate version using .append() method:

Edit in JSFiddle

 
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.

Edit in JSFiddle

 
Here’s alternate version using .load() method:

Edit in JSFiddle

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:

Edit in JSFiddle

 
Alternatively, you can play around with the innerHTML property of Document.head.

Edit in JSFiddle

That’s all about dynamically adding a CSS stylesheet to an HTML page using JavaScript and jQuery.