Home >Web Front-end >JS Tutorial >Introduction to 2 methods of dynamically referencing CSS files in Javascript_Basic knowledge
I recently worked on a project that required JavaScript to dynamically insert styles, but the previous method failed! The reason why I checked for 2 hours turned out to be my poor hands. Let’s talk about this last!
Javascript insertion styles are widely used in front-end development, especially when modifying front-end performance and page skinning. The task I did recently was that when a user clicks a button on someone else's site, a script will be inserted and executed under the page of the other site. This includes the insertion of styles.
Generally, there are two types of JavaScript dynamic insertion styles. One is to introduce external styles into the page and use the tag in
to introduce an external style file. The other is to use < The style> tag inserts the page style (this is not the style attribute).1. Introduce external styles into the page:
Use the tag in
to introduce an external style file. This is relatively simple, and there are no compatibility issues with major browsers:function includeLinkStyle(url) {
var link = document.createElement("link");
link.rel = "stylesheet";
link.type = "text/css";
link.href = url;
document.getElementsByTagName("head")[0].appendChild(link);
}
includeLinkStyle("http://css.jb51.net/home/css/reset.css?v=20101227");
However, in the project I am currently working on, there are very few applied styles. It seems inappropriate to directly introduce an external style file, so I chose the second option, using the