title: Dynamically load css stylesheet and wait for it to load
body: <p>I have a script that detects a button click on which it will attach a CSS stylesheet to the &quot;head&quot; with jQuery like so:</p>
  <pre class="lang-js prettyprint-override"><code>const link = &quot;&lt;link class='listcss' rel='stylesheet' href='http://....list.css'&gt;&quot;;
  $(&quot;head&quot;).append(link);
  </code></pre>
  <p>Then I need to do some calculations based on the css width and height properties:</p>
  <pre><code>function CSSDone(){
              if($(window).width()&gt;640){
                  $(&quot;.grid-item&quot;).css({&quot;height&quot;:$(&quot;.grid-item&quot;).width()*0.2});
                  $(&quot;.grid_item_img&quot;).css({&quot;height&quot;:$(&quot;.grid-item&quot;).width()*0.2});
              console.log(&quot;a&quot;);
              }else{
                  $(&quot;.grid-item&quot;).css({&quot;height&quot;:$(&quot;.grid-item&quot;).width()*0.33});
                  $(&quot;.grid_item_img&quot;).css({&quot;height&quot;:$(&quot;.grid-item&quot;).width()*0.33});
              console.log(&quot;b&quot;);       
              }
          }
          CSSDone();
  </code></pre>
  <p>However, if I launch CSSDone(); right after adding the stylesheet, the calculations happen before the css is loaded.
  I searched the web like crazy but everything I tried doesn't work:</p>
  <p>I tried these options:</p>
  <ol>
  <li><p>Does not work:</p>
  <p>link.onload = function () {
  CSSDone();
  }</p>
  </li>
  <li><p>Does not work:</p>
  <pre><code> if (link.addEventListener) {
     link.addEventListener('load', function() {
       CSSDone();
     }, false);
   }
  </code></pre>
  </li>
  <li><p>Does not work:</p>
  <pre><code> link.onreadystatechange = function() {
     var state = link.readyState;
     if (state === 'loaded' || state === 'complete') {
       link.onreadystatechange = null;
       CSSDone();
     }
   };
  </code></pre>
  </li>
  <li><p>Does not work:</p>
  <pre><code> $(window).load(function () {
       CSSDone();
   });
  </code></pre>
  </li>
  <li><p>Does not work:</p>
  <pre><code> $(window).bind(&quot;load&quot;, function() {
       CSSDone();
   });
  </code></pre>
  </li>
  </ol>
  <p>Believe me. Nothing works......</p>
  <hr>
  **One workaround:**
  <p>I load the css in the DOM and immidiately remove it again with jQuery. That way when adding the link to the head later it's fast enough.</p>