Loading CSS Files with Javascript

In some cases external CSS files needed to be loaded “on demand” rather than including them in the initial HTML markup. In such cases you can use write Javascript code to load the file dynamically.

Creating a new <link> Element

CSS files are referenced by <link> tag in HTML. You can create such a tag with Javascript and append it to the page’s HTML.

// create new link tag
var link = document.createElement('link');

// set properties of link tag

// Loaded successfully
link.onload = function() {

// Loading failed
link.onerror = function() {

// append link element to html

Other things to note :

  • CSS files can be loaded from same or different domain
  • onload and onerror events on the link element can be used to check whether CSS files was loaded successfully or not.
See also  Pure CSS / CSS3 Fullscreen Navigation with Hamburger Toggle

Leave a Reply

Your email address will not be published. Required fields are marked *