TransWikia.com

How to use just appended style link as CSSStylesheet in JavaScript

Stack Overflow Asked by webelf000 on August 5, 2020

I tried to add style link in an HTML page and insert rule

let linklength = document.head.querySelectorAll("link[rel=stylesheet]").length;
let style = document.createElement("link");
style.setAttribute("rel", "stylesheet");
style.setAttribute("type", "text/css");
style.setAttribute("href", "./test.css");
document.head.appendChild(style);
let myStyle = document.styleSheets[linklength];
myStyle.insertRule(".red{color:red}");

But myStyle is undefined and new style didn’t add in document.styleSheets.
I could solve as follows

let linklength = document.head.querySelectorAll("link[rel=stylesheet]").length;
let style = document.createElement("link");
style.setAttribute("rel", "stylesheet");
style.setAttribute("type", "text/css");
style.setAttribute("href", "./test.css");
document.head.appendChild(style);
setTimeout(() => {
    let myStyle = document.styleSheets[linklength];
    myStyle.insertRule(".red{color:red}");
}, 5000);

but I want to insert rule immediately.
I’ve already set timeout 0 milisecond but it didn’t work.

One Answer

The problem is it takes time to download and apply the new stylesheet that you've just added, you need to listen on load event of the new link so you'll able to do something when the new stylesheet loaded.
Working Example :

const link = document.createElement("link");
link.href = "https://code.jquery.com/jquery-3.5.1.min.js"; //your url
console.log(document.styleSheets.length);
link.rel = "stylesheet";
document.head.appendChild(link);
link.addEventListener("load",yourHandler);
function yourHandler(){
   console.log(document.styleSheets.length);
   link.removeEventListener("load",yourHandler);
}

Correct answer by Shawn Vn on August 5, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP