In-depth parsing of dynamically loaded CSS implementation methods

Source: Internet
Author: User
Because the company project needs to use lazy loading to improve the loading speed of the site, the non-first screen rendering necessary CSS files for dynamic loading operations. Next through this article to share the implementation code, the need for a friend reference

I. Method citation sources and applications

This dynamically loaded CSS method Loadcss, stripped from Sea.js, and made further optimizations (optimization code will be analyzed later).

Because the company project needs to use lazy loading to improve the loading speed of the site, the non-first screen rendering necessary CSS files for dynamic loading operations.

Second, the complete code after optimization

/** @function Dynamically loading CSS file * @param {string} options.url--CSS Resource path * @param {function} Options.callback--post-load callback function * @param {St Ring} options.id--Link tag id*/function loadcss (options) {var url = options.url, callback = typeof Options.callba CK = = "function"? Options.callback:function () {}, id = options.id, node = document.createelement ("link"), Supportonloa D = "onload" in node, Isoldwebkit = +navigator.useragent.replace (/.* (?: applewebkit| Androidwebkit) \/? (\d+). */i, "$") < 536,//WebKit old kernel do special processing protectnum = 300000;    Threshold of 10 minutes, one second to execute pollcss 500 times Node.rel = "stylesheet";    Node.type = "Text/css";    Node.href = URL;    if (typeof ID!== "undefined") {node.id = ID;    } document.getelementsbytagname ("Head") [0].appendchild (node); WebKit and Old Firefox if (Isoldwebkit | |!supportonload) {//Begin after node insertion sett        Imeout (function () {POLLCSS (node, callback, 0);        }, 1); ReTurn        } if (supportonload) {node.onload = onload;        Node.onerror = function () {//load failed (404) onload ();                }}else{Node.onreadystatechange = function () {if (/loaded|complete/.test (node.readystate)) {            OnLoad (); }}} function onload () {//Make sure to run only one download operation node.onload = Node.onerror = Node.onreadystatechange =        Null        Emptying the node reference, in the low version of IE, does not clear will cause a memory leak node = NULL;    Callback ();    }//loop to determine if the CSS has been loaded successfully */* @param node--Link node * @param callback--callback function * @param step-pedometer, avoid infinite loop */        function pollcss (node, callback, Step) {var sheet = node.sheet, isLoaded;        Step + = 1;            protection, greater than 10 minutes, then no longer polls if (step > Protectnum) {isLoaded = true;            Empty node refers to node = NULL;            Callback ();        Return } if (Isoldwebkit) {//For WebKit < 536 if (Sheet) {isLoaded = true;                    }}else if (sheet) {//For Firefox < 9.0 try{if (sheet.cssrules) {                IsLoaded = true; }}catch (ex) {///Firefox special version, through a specific value to know whether the download succeeded//The value of ' Ex.name ' is changed from " Ns_error_dom_security_err "//To" Securityerror "since Firefox 13.0.                But Firefox was less than 9.0//in here, so it's OK to just rely on "ns_error_dom_security_err"                if (ex.name = = = "Ns_error_dom_security_err") {isLoaded = true;                }}} setTimeout (function () {if (isLoaded) {//delay 20ms is to leave the downloaded style enough time to render            Callback ();            }else{pollcss (node, callback, step);    }}, 20); }}

Third, the parsing code

First, the parameters

This method supports three parameters and can be extended.

1.1 Opations.url

A URL is a CSS resource path that needs to be introduced, which is the href attribute content of the tag.

1.2 Options.id

ID is the id attribute of the label. This parameter is a non-essential parameter and can not be passed. The main role is to mark the current label, convenient JS to find, to determine whether a CSS file has been loaded.

1.3 Options.callback

Callback is the callback function that will be called when the CSS file is loaded. There are special scenarios where the file load fails and the callback function is still executing.

Second, generate tags, and insert head, load resources

var url = options.url,    callback = typeof Options.callback = = "function"? Options.callback:function () {},    id = op Tions.id,    node = document.createelement ("link"), Node.rel = "stylesheet"; node.type = "Text/css"; node.href = Url;if ( typeof ID!== "undefined") {    node.id = ID;} document.getElementsByTagName ("Head") [0].appendchild (node);

Generate a DOM node, and then configure the required attribute values such as rel, type, href, and so on, so that the browser can parse the linked resource normally.

Next, find the head node and insert the node.

Third, the realization of CSS resources Download status Monitoring Pollcss method

The responsibility of the Pollcss method is to judge the inserted link node, which is whether the node variable feedback resource has been loaded.

3.1 Main basis of the judgment

Browser load CSS Resources, will give the link node generated sheet properties, can be different from the browser, read the sheet property related content, to determine whether the load is complete. So the first sentence of the var sheet = Node.sheet First thing to do is to get the sheet property value.

3.2 General browser judgment

try{    if (sheet.cssrules) {        isLoaded = true;    }} catch (ex) {    ///Firefox special version, through a specific value to know if the download succeeded    //The value of ' Ex.name ' is changed from "Ns_error_dom_security_err"    // To "Securityerror" since Firefox 13.0. But Firefox was less than 9.0    //In here, so it's OK to just rely on "Ns_error_dom_security_err"    if (ex.name = = = "N S_error_dom_security_err ") {        isLoaded = true;    }}

If the read sheet.cssrules has a value, it proves that the CSS resource has been linked into the page and begins parsing. You can now tell that the resource was successfully loaded.

If the read fails, the specific name attribute Ex.name = = = "Ns_error_dom_security_err" is determined based on the error-throwing content. exists, it is the low version of Firefox (9.0 ago) and the resource has been loaded successfully.

3.3 Old WebKit Kernel browser judgment

var isoldwebkit = +navigator.useragent.replace (/.* (?: applewebkit| Androidwebkit) \/? (\d+). */i, "$") < 536; WebKit the old kernel does special processing if (Isoldwebkit) {    //for WebKit < 536    if (sheet) {        isLoaded = true;    }}

If the old kernel browser is WebKit, you only need to determine if the sheet attribute value exists, which means the resource load is complete.

3.4 Increased multiple cycle detection

SetTimeout (function () {    if (isLoaded) {        //delay 20ms is to leave the downloaded style enough time to render        callback ();    } else{        pollcss (node, callback, step);    }}, 20);

After the Pollcss method is triggered, the sheet value may be detected for the first time and will not be detected. The representative has not yet finished loading. So polling is required. This is a 20ms query until the resource load is complete.

3.5 Polling fault tolerance (optimized for sea.js source code)

CSS resource loading is also possible when errors occur, and there is a possibility of not triggering the OnError method. If you do not add a protection, the polling may persist, so a limit threshold is required.

var protectnum = 300000,//threshold 10 minutes, one second to execute POLLCSS 500 times    step = 0;//Many codes .... step + = 1;//protection, greater than 10 minutes, no longer poll if (Step > Prot Ectnum) {    isLoaded = true;    Empty node refers to    node = null;    Callback ();    return;}

The threshold here is poll 10 minutes, if after 10 minutes, still not eligible, then the default resource has been downloaded complete, execute the callback method, and empty the node reference.

Iv. determining the timing of triggering pollcss inspections

4.1 Pollcss Polling Application scenario

The POLLCSS is used for polling when the browser kernel is the old WebKit kernel, or when the node triggers the OnLoad method is not supported.

For-old WebKit and old firefoxif (Isoldwebkit | |!supportonload) {    //Begin after node insertion    setTimeout (fun Ction () {        pollcss (node, callback, 0);    }, 1);    return;}

Five, modern browser directly with OnLoad and onreadystatechange to make judgments

Modern browsers in this way to judge, you can avoid the disadvantages of polling. Judgment is also more accurate and timely.

5.1 OnLoad method

function onload () {    //Make sure to run only one download operation    node.onload = Node.onerror = Node.onreadystatechange = null;    Emptying the node reference, in the low version of IE, does not clear will cause a memory leak    node = null;    Callback ();}

After the OnLoad method triggers execution, multiple related methods should be reset immediately to avoid callback multiple triggers.

node = NULL; resets node to NULL in order to avoid memory overflow problems in the low version of IE, and to clean up unused DOM nodes in a timely manner.

Finally, execute the callback method.

5.2 Support for OnLoad method browser processing

if (supportonload) {    node.onload = onload;    Node.onerror = function () {        //load failed (404)        onload ();}    }

5.3 Handling of the OnLoad method browser is not supported

if (supportonload) {    //code ...} else{    node.onreadystatechange = function () {        if (/loaded|complete/.test (node.readystate)) {            onload ();        }    }}

Iv. PostScript

Choose Peel Sea.js method to transform the reason: Because the JS Library uses a wide range of people, if the problem, the author will be repaired in time. Therefore, the code as a blueprint for the transformation to fit the company's user base, to avoid large areas of problems.

The above is a small series to introduce you to the in-depth analysis of dynamic loading CSS implementation method, I hope that we have some help, if you have any questions please give me a message, small series will promptly reply to you. Thank you very much for your support for topic.alibabacloud.com!

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.