简体   繁体   中英

load css file using javascript

I'm new to javascript. I'm trying to load a .css file using the following javascript code, but it seems not working.

var myCss = document.createElement("link");
myCss.type = "text/css";
myCss.rel = "stylesheet";
myCss.href = "mycss.css";
document.getElementsByTagName("head")[0].appendChild(myCss);

Can anyone help? thanks.

You have in stackoverflow another question about it, you can find it here: How to load up CSS files using Javascript?

Which is a "oldschool" way to do it, just like user58777 said. (Credits go to him)

His code:

var $ = document; // shortcut
var cssId = 'myCss';  // you could encode the css path itself to generate id..
if (!$.getElementById(cssId))
{
    var head  = $.getElementsByTagName('head')[0];
    var link  = $.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);
}

Why are you trying to do this? What benefit are you expecting?

I've never come across a situation where this is a good idea. CSS files are usually pretty small, so you aren't really gaining much by loading them dynamically. Just do the load in the head tag.

Anyway, the code you have should work. Just be sure that path is correct (it will be relative to the html file you're running)


Another solution would be to load an html file with all of the markup you need, and append it to the body. Check out the jQuery.load function The line below will load gameMarkup.html into the body tag.

$( "body" ).load( "gameMarkup.html" );

You can include all of the markup for your game here (not just styles). Generating elements with js can be useful, but it makes the code harder to maintain.

If you aren't using jquery, you can do the same thing with XHR , but it will be a lot more lines of code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM