JavaScript implements a scheme for dynamically creating CSS style rules

  • 2020-03-30 03:53:50
  • OfStack

There's a lot of JavaScript code in Web applications today, and we're always looking for solutions to make them faster.

1. We use more efficient (link: http://davidwalsh.name/event-delegate) allows event listeners,
2. We use (link: http://davidwalsh.name/function-debounce) to limit the number of the given method is invoked over a period of time, please refer to: (link: #)
3. We use (link: http://davidwalsh.name/curljs) to load we really need that part of the resources, and so on.

Another way to make our pages faster and more efficient is to dynamically add and remove styles from our stylesheets directly through JS, instead of constantly querying DOM elements and applying styles. Here's how it works.

Get style sheet

You can select any style sheet to add style rules. If you have a certain style sheet, you can give < Link> Or < Style> The tag adds an ID attribute, and you get the CSSStyleSheet object directly from the sheet attribute of the DOM element. StyleSheets can also be traversed through document.stylesheets to:


//Returns an Array-like style list named arrays
var sheets = document.styleSheets; /*
The return value looks like this :  StyleSheetList
{
    0: CSSStyleSheet,
    1: CSSStyleSheet,
    2: CSSStyleSheet,
    3: CSSStyleSheet,
    4: CSSStyleSheet,
    length: 5,
    item: function
}
*/ //Get the first sheet, regardless of the media property
var sheet = document.styleSheets[0];

Special attention is paid to the media properties of the stylesheet -- you can't add CSS rules to a printed stylesheet when you want to display them on the screen. Take a closer look at the CSSStyleSheet attributes:


//The console outputs information for the first stylesheet
console.log(document.styleSheets[0]); /*
The return value :  CSSStyleSheet
    cssRules: CSSRuleList[ object ]
    disabled: false
    href: "http://davidwalsh.name/somesheet.css"
    media: MediaList[ object ]
    ownerNode: link[ object ]
    ownerRule: null
    parentStyleSheet: null
    rules: CSSRuleList[ object ]
    title: null
    type: "text/css"
*/ //Gets media type
console.log(document.styleSheets[0].media.mediaText)
/*
The return value might be :
    "all" or "print" Or something else that applies to this style sheet media
*/

In all cases, you will have a way to get the stylesheet to which you want to add the rule.

Create a new style sheet

In many cases, the best approach may be to create a new one. Style> Element to hold these dynamic rules. It's also very simple:


var sheet = (function() {
    //Create <Style> The tag < br / >     var style = document.createElement("style");     //You can add a media (/ media query,media query) attribute
    // style.setAttribute("media", "screen")
    // style.setAttribute("media", "only screen and (max-width : 1024px)")     //For WebKit hacks :(
    style.appendChild(document.createTextNode(""));
    //Will <Style> The
element is added to the page     document.head.appendChild(style);     return style.sheet;
})();

The tragedy of WebKit is that it takes a bit of a hack to create it properly, but all we need to care about is this sheet.

Insert the rules

The insertRule method of Stylesheets was not available in earlier versions of IE, although this is now the standard for rule injection. The insertRule method needs to write the entire CSS rule, just as it does in the stylesheet:


sheet.insertRule("header { float: left; opacity: 0.8; }", 1);

This JavaScript API method may seem a little clunky, but that's exactly how it works. The second parameter, index, indicates where the rule is to be inserted (the index). This is also useful so that you can insert the same rule/code, which allows later rules to take effect. The default index is -1, which represents the end of the entire collection. If you want to have extra/lazy control rules, you can also add them! The important flag goes to a rule to avoid indexing problems.

AddRule -- non-standard addRule method

The CSSStyleSheet object has an addRule method that allows you to register CSS rules into a style sheet. The addRule method takes three arguments: the first argument is the selector, the second argument is the CSS rule code, and the third argument is an integer index starting at 0, indicating the position of the style (in the same selector) :


sheet.addRule("#myList li", "float: left; background: red !important;", 1);

The return value of the addRule method is always -1, so this value doesn't really mean anything.
Remember, the advantage of this approach is that the elements you add from the page automatically have styles that apply to them, meaning you don't have to add them to specific elements, but instead inject them directly into the page. More efficient!

Safety application rules

This tool method should cover all situations where a new style rule is added. If you are worried about making an error in your application, you should wrap the code for this method in a try{} catch(e){} block.

Insert media query rules

Media query rules can be added in two ways. The first is to use the standard insertRule method:


sheet.insertRule(
  "@media only screen and (max-width : 1140px) { header { display: none; } }"
  );

Adding rules to stylesheets on the fly is an efficient way to do this, and it may be easier than you think. Keep in mind that this scenario may be needed for your next big application, because it prevents you from falling into a pit in both the code and the element handling.


Related articles: