How to load up CSS files using Javascript?

后端 未结 19 3255
栀梦
栀梦 2020-11-21 07:51

Is it possible to import css stylesheets into a html page using Javascript? If so, how can it be done?

P.S the javascript will be hosted on my site, but I want users

相关标签:
19条回答
  • 2020-11-21 08:08
    var fileref = document.createElement("link")
    fileref.setAttribute("rel", "stylesheet")
    fileref.setAttribute("type", "text/css")
    fileref.setAttribute("th:href", "@{/filepath}")
    fileref.setAttribute("href", "/filepath")
    

    I'm using thymeleaf and this is work fine. Thanks

    0 讨论(0)
  • 2020-11-21 08:09

    Element.insertAdjacentHTML has very good browser support, and can add a stylesheet in one line.

    document.getElementsByTagName("head")[0].insertAdjacentHTML(
        "beforeend",
        "<link rel=\"stylesheet\" href=\"path/to/style.css\" />");
    
    0 讨论(0)
  • 2020-11-21 08:10

    In a modern browser you can use promise like this. Create a loader function with a promise in it:

    function LoadCSS( cssURL ) {
    
        // 'cssURL' is the stylesheet's URL, i.e. /css/styles.css
    
        return new Promise( function( resolve, reject ) {
    
            var link = document.createElement( 'link' );
    
            link.rel  = 'stylesheet';
    
            link.href = cssURL;
    
            document.head.appendChild( link );
    
            link.onload = function() { 
    
                resolve(); 
    
                console.log( 'CSS has loaded!' ); 
            };
        } );
    }
    

    Then obviously you want something done after the CSS has loaded. You can call the function that needs to run after CSS has loaded like this:

    LoadCSS( 'css/styles.css' ).then( function() {
    
        console.log( 'Another function is triggered after CSS had been loaded.' );
    
        return DoAfterCSSHasLoaded();
    } );
    

    Useful links if you want to understand in-depth how it works:

    Official docs on promises

    Useful guide to promises

    A great intro video on promises

    0 讨论(0)
  • 2020-11-21 08:11

    I know this is a pretty old thread but here comes my 5 cents.

    There is another way to do this depending on what your needs are.

    I have a case where i want a css file to be active only a while. Like css switching. Activate the css and then after another event deativate it.

    Instead of loading the css dynamically and then removing it you can add a Class/an id in front of all elements in the new css and then just switch that class/id of the base node of your css (like body tag).

    You would with this solution have more css files initially loaded but you have a more dynamic way of switching css layouts.

    0 讨论(0)
  • 2020-11-21 08:14

    Here's a one line example, that uses plain JavaScript to inject a CSS link into the head element based on the filename portion of the URL:

    document.head.innerHTML += '<link rel="stylesheet" href="css/style.css">';

    Most browsers support it. See the browser compatibility.

    0 讨论(0)
  • 2020-11-21 08:15

    Here's a way with jQuery's element creation method (my preference) and with callback onLoad:

    var css = $("<link>", {
      "rel" : "stylesheet",
      "type" :  "text/css",
      "href" : "style.css"
    })[0];
    
    css.onload = function(){
      console.log("CSS IN IFRAME LOADED");
    };
    
    document
      .getElementsByTagName("head")[0]
      .appendChild(css);
    
    0 讨论(0)
提交回复
热议问题