javascriptcssimageonloadonload-event

How to run a function when CSS stylesheet finishes loading


How do I run a function when a stylesheet finishes loading?

Here is my code..

var d = document,
    css = d.head.appendChild(d.createElement('link'))

css.rel = 'stylesheet';
css.type = 'text/css';
css.href = "https://unpkg.com/tachyons@4.10.0/css/tachyons.css"

Solution

  • According to MDN's <link>: The External Resource Link element,

    You can determine when a style sheet has been loaded by watching for a load event to fire on it; similarly, you can detect if an error has occurred while processing a style sheet by watching for an error event:

    <script>
    var myStylesheet = document.querySelector('#my-stylesheet');
    
    myStylesheet.onload = function() {
      // Do something interesting; the sheet has been loaded
    }
    
    myStylesheet.onerror = function() {
      console.log("An error occurred loading the stylesheet!");
    }
    </script>
    
    <link rel="stylesheet" href="mystylesheet.css" id="my-stylesheet">
    

    Note: The load event fires once the stylesheet and all of its imported content has been loaded and parsed, and immediately before the styles start being applied to the content.