How to load up CSS files using Javascript?

后端 未结 19 3256
栀梦
栀梦 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 07:59

    Have you ever heard of Promises? They work on all modern browsers and are relatively simple to use. Have a look at this simple method to inject css to the html head:

    function loadStyle(src) {
        return new Promise(function (resolve, reject) {
            let link = document.createElement('link');
            link.href = src;
            link.rel = 'stylesheet';
    
            link.onload = () => resolve(link);
            link.onerror = () => reject(new Error(`Style load error for ${src}`));
    
            document.head.append(link);
        });
    }
    

    You can implement it as follows:

    window.onload = function () {
        loadStyle("https://fonts.googleapis.com/css2?family=Raleway&display=swap")
            .then(() => loadStyle("css/style.css"))
            .then(() => loadStyle("css/icomoon.css"))
            .then(() => {
                alert('All styles are loaded!');
            }).catch(err => alert(err));
    }
    

    It's really cool, right? This is a way to decide the priority of the styles using Promises.

    To see a multi-style loading implementation see: https://stackoverflow.com/a/63936671/13720928

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

    There is a general jquery plugin that loads css and JS files synch and asych on demand. It also keeps track off what is already been loaded :) see: http://code.google.com/p/rloader/

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

    Here's the "old school" way of doing it, which hopefully works across all browsers. In theory, you would use setAttribute unfortunately IE6 doesn't support it consistently.

    var cssId = 'myCss';  // you could encode the css path itself to generate id..
    if (!document.getElementById(cssId))
    {
        var head  = document.getElementsByTagName('head')[0];
        var link  = document.createElement('link');
        link.id   = cssId;
        link.rel  = 'stylesheet';
        link.type = 'text/css';
        link.href = 'http://website.com/css/stylesheet.css';
        link.media = 'all';
        head.appendChild(link);
    }
    

    This example checks if the CSS was already added so it adds it only once.

    Put that code into a javascript file, have the end-user simply include the javascript, and make sure the CSS path is absolute so it is loaded from your servers.

    VanillaJS

    Here is an example that uses plain JavaScript to inject a CSS link into the head element based on the filename portion of the URL:

    <script type="text/javascript">
    var file = location.pathname.split( "/" ).pop();
    
    var link = document.createElement( "link" );
    link.href = file.substr( 0, file.lastIndexOf( "." ) ) + ".css";
    link.type = "text/css";
    link.rel = "stylesheet";
    link.media = "screen,print";
    
    document.getElementsByTagName( "head" )[0].appendChild( link );
    </script>
    

    Insert the code just before the closing head tag and the CSS will be loaded before the page is rendered. Using an external JavaScript (.js) file will cause a Flash of unstyled content (FOUC) to appear.

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

    I guess something like this script would do:

    <script type="text/javascript" src="/js/styles.js"></script>
    

    This JS file contains the following statement:

    if (!document.getElementById) document.write('<link rel="stylesheet" type="text/css" href="/css/versions4.css">');
    

    The address of the javascript and css would need to be absolute if they are to refer to your site.

    Many CSS import techniques are discussed in this "Say no to CSS hacks with branching techniques" article.

    But the "Using JavaScript to dynamically add Portlet CSS stylesheets" article mentions also the CreateStyleSheet possibility (proprietary method for IE):

    <script type="text/javascript">
    //<![CDATA[
    if(document.createStyleSheet) {
      document.createStyleSheet('http://server/stylesheet.css');
    }
    else {
      var styles = "@import url(' http://server/stylesheet.css ');";
      var newSS=document.createElement('link');
      newSS.rel='stylesheet';
      newSS.href='data:text/css,'+escape(styles);
      document.getElementsByTagName("head")[0].appendChild(newSS);
    }
    //]]>
    
    0 讨论(0)
  • 2020-11-21 08:05

    The YUI library might be what you are looking for. It also supports cross domain loading.

    If you use jquery, this plugin does the same thing.

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

    use:

    document.getElementById("of head/body tag")
            .innerHTML += '<link rel="stylesheet" type="text/css" href="style.css">';
    
    0 讨论(0)
提交回复
热议问题