title: How to use just appended style link as CSSStylesheet in JavaScript
body: <p>I tried to add style link in an HTML page and insert rule</p>
  <pre><code>let linklength = document.head.querySelectorAll(&quot;link[rel=stylesheet]&quot;).length;
  let style = document.createElement(&quot;link&quot;);
  style.setAttribute(&quot;rel&quot;, &quot;stylesheet&quot;);
  style.setAttribute(&quot;type&quot;, &quot;text/css&quot;);
  style.setAttribute(&quot;href&quot;, &quot;./test.css&quot;);
  document.head.appendChild(style);
  let myStyle = document.styleSheets[linklength];
  myStyle.insertRule(&quot;.red{color:red}&quot;);
  </code></pre>
  <p>But myStyle is undefined and new style didn't add in document.styleSheets.
  I could solve as follows</p>
  <pre><code>let linklength = document.head.querySelectorAll(&quot;link[rel=stylesheet]&quot;).length;
  let style = document.createElement(&quot;link&quot;);
  style.setAttribute(&quot;rel&quot;, &quot;stylesheet&quot;);
  style.setAttribute(&quot;type&quot;, &quot;text/css&quot;);
  style.setAttribute(&quot;href&quot;, &quot;./test.css&quot;);
  document.head.appendChild(style);
  setTimeout(() =&gt; {
      let myStyle = document.styleSheets[linklength];
      myStyle.insertRule(&quot;.red{color:red}&quot;);
  }, 5000);
  </code></pre>
  <p>but I want to insert rule immediately.
  I've already set timeout 0 milisecond but it didn't work.</p>