JavaScript implementation dynamically create CSS style rule scheme _javascript tips

Source: Internet
Author: User

There's a lot of JavaScript code in Web Apps right now, and we've been chasing a variety of solutions that make them faster.

1. We use event delegation to make event monitoring more efficient,
2. We use function debouncing to limit the number of times a given method is invoked for a period of time, refer to how to prevent high-frequency triggering of event functions (Chinese translation)
3. We use the JavaScript loader to load the part of the resources we really need, and so on.

There is also a way to make our pages faster and more efficient. It is to dynamically add and remove some styles from the stylesheet directly through JS, instead of constantly querying DOM elements and applying various styles. Here's how it works.

Get style sheet

You can select any style sheet to add a style rule. If you have a certain style sheet, you can add an id attribute to the <link> or <style> tag in an HTML page and then get the Cssstylesheet object directly from the sheet property of the DOM element. The stylesheet can also be traversed through document.stylesheets to:

Copy Code code as follows:

Returns an array-like List of (array-like) styles Stylesheetlist
var sheets = document.stylesheets;

/*
The return value is similar to the following:

Stylesheetlist
{
0:cssstylesheet,
1:cssstylesheet,
2:cssstylesheet,
3:cssstylesheet,
4:cssstylesheet,
Length:5,
Item:function
}
*/

Get the first sheet, regardless of media properties
var sheet = document.stylesheets[0];

What you need to pay special attention to is the media properties of the stylesheet--you can't add CSS rules to a print style sheet when you want to display them on the screen. You can take a closer look at the property information for the Cssstylesheet object:

Copy Code code as follows:

Console output information for the first style sheet
Console.log (Document.stylesheets[0]);

/*
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"
*/

Getting media type (medium type)
Console.log (Document.stylesheets[0].media.mediatext)
/*
The return value may be:
' All ' or ' print ' or other media that is applied to this style sheet
*/

In all cases, you must have a way to get the style sheet that you want to add the rule to.

Create a new style sheet

In many cases, the best approach might be to create a new <style> element to store these dynamic rules. This is also very simple:

Copy Code code as follows:

var sheet = (function () {
Create <style> Label
var style = document.createelement ("style");

You can add a media (/media Query) property
Style.setattribute ("Media", "screen")
Style.setattribute ("Media", "only screen and (max-width:1024px)")

:(of WebKit hack
Style.appendchild (document.createTextNode (""));


Add <style> elements to the page
Document.head.appendChild (style);

return style.sheet;
})();

The tragedy is that WebKit needs a little hack to create it correctly, but we only need to care about this sheet.

Insert Rule

The stylesheets Insertrule method in earlier versions of IE was not available, although this is now the standard for rule injection. The Insertrule method needs to write the entire CSS rule, as it does in the style sheet:

Copy Code code as follows:

Sheet.insertrule ("header {float:left; opacity:0.8; } ", 1);

This JavaScript API method looks a bit earthy, but it does run like this. The second argument index represents the location (index) where the rule is to be inserted. This is also useful so that you can insert the same rule/code, which allows the backend rule to take effect. The default index is-1, which represents the end of the entire collection. If you want to have additional/lazy control rules, you can also add!important tags to a rule to avoid indexing problems.

Add a rule--nonstandard addrule method

The Cssstylesheet object has a Addrule method that allows you to register the CSS rules into the style sheet. The Addrule method accepts three parameters: the first parameter is the selector (selector), the second parameter is the CSS rule code, and the third is an integer index starting at 0, representing the position of the style (in the same selector):

Copy Code code as follows:

Sheet.addrule ("#myList li", "FLOAT:LEFT; Background:red!important; ", 1);

The return value of the Addrule method is always-1, so this value has no practical significance.
Remember, the advantage of this approach is that the elements added from the page automatically have the styles that apply to them, meaning that you don't have to add them to the specific elements, but instead inject them directly into the page. Of course more efficient!

Security Application Rules

Because not all browsers support the Insertrule method, it is a good idea to create a wrapper function to handle the rule application. Here is a quick method of soil:

Copy Code code as follows:

function Addcssrule (sheet, selector, rules, index) {
if ("Insertrule" in sheet) {
Sheet.insertrule (selector + "{" + Rules + "}", index);
}
else if ("addrule" in sheet) {
Sheet.addrule (selector, rules, index);
}
}

How to use
Addcssrule (Document.stylesheets[0], "header", "Float:left");

This tool method should cover all of the new style rules. If you are concerned about an error in your application, you should wrap the method's code with a try{} catch (e) {} block.

Insert Media Query rules

There are two ways to add a media query rule. The first is to use the standard Insertrule method:

Copy Code code as follows:

Sheet.insertrule (
"@media only screen and (max-width:1140px) {header {Display:none}}}"
);

Of course, because the older version of IE does not support insertrule, an alternative is to create a STYLE element, specify the appropriate media properties, and then add the style to the new style sheet. This may require the use of multiple STYLE elements, but it is also easy. I might create an object that specifies media queries as well as indexes, and that creates/acquires them.

Dynamically adding a rule to a stylesheet is an efficient tool that may be simpler than you might think. Keep in mind that this scenario may need to be used in your next big application because it can prevent you from falling into a hole in both code and element handling.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.