How to load CSS files using JavaScript?



Sometimes, the task is change the page themes and to use different CSS files on the same page content. In such tasks the need is to fetch a CSS and load it dynamically while selecting a theme. In this case the CSS file has to be accessed, loaded and even selected through a javascript program. Using HTML and javascript code this process of loading the CSS file is demonstrated in this article. This is shown by using two different examples. In the first example, a CSS file is selected on the windows load event. In the second example, two buttons are used to load separate CSS files on button clicks.

Example 1: Loading the CSS file on window.onload( )

Folder and Pages Design Steps ?

  • Step 1 ? Make an html file and start writing the code. Create a CSS file and define the styles for background, p tag and h1 tag.

  • Step 2 ? Inside the

    Example 1

    To load the CSS file using JS

    Code For cssfilenew.css

    body {
       background-color: rgb(110, 187, 197);
    }
    h1 {
       color: rgb(15, 15, 87);
    }
    p {
       color: rgb(197, 31, 31);
    }
    

    Viewing The Result

    For seeing the result open the html file in a browser. The styles will be included in the CSS file that is loaded using Javascript.

    Example2: Loading the different CSS files on click of two buttons

    Folder and Pages Design Steps ?

    Step 1 ? Make an HTML file and start writing the code. Create two CSS files and define the different styles for the background, p tag, and h1 tag in these.

    Step 2 ? Inside the

    Example 1

    To load the CSS file using JS

    Code For cssfile.css

    body {
       background-color: rgb(167, 197, 110);
    }
    h1 {
       color: rgb(87, 15, 55);
    }
    p {
       color: rgb(4, 59, 20);
    }
    

    Code For cssfilenew.css

    body {
       background-color: rgb(110, 187, 197);
    }
    h1 {
       color: rgb(15, 15, 87);
    }
    p {
       color: rgb(197, 31, 31);
    }
    

    Viewing The Result

    For seeing the result open the html file in a browser. The styles will be included from the CSS files that are loaded on button clicks.

    3In this article, using two different examples, the ways to show how to load the CSS file dynamically using the javascript code are given. First, the method is given where a CSS file is selected when the page is loaded and then the way of using the CSS files on button click is given. For this two buttons are clicked to load different CSS files and change the style of the same page.

Updated on: 2023-04-18T15:23:15+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements