js insert public css, load css asynchronously

The general style code will be introduced at the beginning of the document, and will be loaded synchronously when the document is loaded.
Regardless of whether the user can use it for this operation or not, the style code will all be loaded in

But if you want to load css asynchronously, or insert a newly generated css, there are ways to achieve it.

Insert public css code block

  • Use createElement a style node
  • Use innerHTML to enter the required css code
  • Insert body.appendChild into the head
var new_element = document.createElement("style");
new_element.innerHTML = ("* { font-size: 28px; }");
document.head.appendChild(new_element);

* The content of the original js method of inserting public css




Insert a link reference

  • A link node with createElement
  • Set the address of the css file you want to load, and related properties
  • Insert body.appendChild into the head
var new_element = document.createElement("link");
new_element.rel = "stylesheet"
new_element.type = "text/css"
new_element.href = "css/scss.css"
document.head.appendChild(new_element);



The principles of the two methods are similar, but the properties are different. The
former is to insert non-existent styles, such as when the user selects the color system, brightness, main color, etc. The
latter is to add the designed style to the document in an asynchronous manner.

end

Guess you like

Origin blog.csdn.net/u013970232/article/details/113606319