How to load up CSS files using Javascript?VanillaJS

2022-08-29 23:39:22

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 to be able to put in the tag of their website, and it should be able to import a css file hosted on my server into the current web page. (both the css file and the javascript file will be hosted on my server).<head>


答案 1

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

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.example/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 element based on the filename portion of the URL:head

<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 tag and the CSS will be loaded before the page is rendered. Using an external JavaScript () file will cause a Flash of unstyled content (FOUC) to appear.head.js


答案 2

If you use jquery:

$('head').append('<link rel="stylesheet" type="text/css" href="style.css">');