Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here's the "old school" way of doing it, which hopefully works across all browsers. In theory, you would use <code>setAttribute</code> unfortunately IE6 doesn't support it consistently.</p> <pre><code>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); } </code></pre> <p>This example checks if the CSS was already added so it adds it only once.</p> <p>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.</p> <h1>VanillaJS</h1> <p>Here is an example that uses plain JavaScript to inject a CSS link into the <code>head</code> element based on the filename portion of the URL:</p> <pre><code>&lt;script type="text/javascript"&gt; 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 ); &lt;/script&gt; </code></pre> <p>Insert the code just before the closing <code>head</code> tag and the CSS will be loaded before the page is rendered. Using an external JavaScript (<code>.js</code>) file will cause a Flash of unstyled content (<a href="http://en.wikipedia.org/wiki/Flash_of_unstyled_content" rel="noreferrer">FOUC</a>) to appear.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload