Javascript dynamic loading of CSS style elements

Source: Internet
Author: User
  • Http://www.loveyuki.com/Article/Javascript_Load_Style_Elements.aspx

  • It is easy to dynamically load a CSS file using JavaScript, but if you want to load a CSS style element, writing some CSS statements in it is not that easy. However, it's hard not to mention that we can check the msdn and Mozilla development websites. The following statements are compatible with IE, Firefox, Safari, and opera.

  •  

     

    1   Function Attachstyle (owndoc, stycss) {
    2 VaR Elmsty = Owndoc. createelement ( ' Style ' );
    3 Elmsty. setattribute ( " Type " , " Text/CSS " );
    4 If (Elmsty. stylesheet) {
    5Elmsty.stylesheet.css text=Stycss;
    6}   Else   {
    7Elmsty. appendchild (owndoc. createtextnode (stycss ));
    8}
    9 Owndoc. getelementsbytagname ( " Head " )[ 0 ]. Appendchild (elmsty );
    10 }  

     

    This writing method is not scientific. Do you think it is OO? It is not flexible and not suitable for asynchronous Ajax reprinting! Slight contempt!

    It is best to use the CSS external import method to load!

     

    1   Function Attachstyle () {
    2   This . Load = Function (URL) {
    3 VaR CSS = Document. createelement ( ' Link ' );
    4 CSS. Type = " Text/CSS " ;
    5 CSS. rel = " = " Stylesheet " ;
    6 CSS. src = URL;
    7 VaR head = Document. getelementsbytagname ( " Head " ) [0];
    8 Head. appendchild (CSS );
    9 VaR self = this;
    10
    11 CSS. onload = CSS. onreadystatechange = function (){
    12 If (this. readystate & this. readystate = " Loading " ) Return;
    13 Self. onsuccess ();
    14 }
    15 CSS. onerror = function (){
    16 Head. removechild ();
    17 Self. onfailure ();
    18 }
    19 }
    20 This. onsuccess = function () {}// events of Successful loading
    21 This. onfailure = function () {}// loading failure event
    22 }
    23

     

     

     

     

     

    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.