简体   繁体   中英

Return stylesheet from external js file

I'm using the JavaScript below to decide which style sheet to load (my Christmas style loads if it's December, otherwise my default style loads). This is causing problems with the XHTML validation, I suspect the best solution would be to load the js from an external file but I'm fairly new to this and can't for the life of me get this to work.

I'd like, if possible, to use the same code but in a separate file to achieve the same effect as having it execute directly in the HTML. If someone could explain how to do this it would be much appreciated!

<head>
<script type="text/javascript">
    var i = new Date();
    var m = i.getMonth();
    if (m==11) {
        document.write('<link rel="stylesheet" type="text/css" href="mystyle-christmas.css" />');
    } else {
        document.write('<link rel="stylesheet" type="text/css" href="mystyle-default.css" />');
    }
</script>
</head>

You might wanna use the DOM functions to create a LINK node and add that to the header instead.

var l = document.createElement('LINK');
l.setAttribute('rel','stylesheet');
l.setAttribute('href','mystyle-christmas.css');
l.type = 'text/css';
document.getElementsByTagName('HEAD')[0].appendChild(l);
<link id="stylesheet" rel="stylesheet" type="text/css" href="mystyle-default.css" />

var i = new Date();
var m = i.getMonth();
if (m>=11) {
document.getElementById('stylesheet').href = 'mystyle-christmas.css';
} 

The default stylesheet does not need to be loaded with javascript, you only replace the stylesheet during month(s) needed.

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