Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Can you please help me use javascript to load CSS files based on URL parameters?

I have 3 parameters (one, two, and three) and I have 3 CSS files.

if (window.location.search.search(/[?&]parameter=one(?:$|&)/) !== -1) 
{
             What code should go in there to load the css?
}

Should the JS be held in the header of the HTML file?

share|improve this question
    
here's an example stackoverflow.com/a/577002/1113766 –  Juan C. Feb 18 '14 at 17:05
    
possible duplicate of How to load up CSS files using Javascript? –  apaul34208 Feb 19 '14 at 2:08

1 Answer 1

if (window.location.search.search(/[?&]parameter=one(?:$|&)/) !== -1) {

    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 = 'css/one.css';
        link.media = 'all';
        head.appendChild(link);
    }

}
else if(window.location.search.search(/[?&]parameter=two(?:$|&)/) !== -1)
{
     //Another way & More simple
     var ss = document.createElement("link");
     ss.type = "text/css";
     ss.rel = "stylesheet";
     ss.href = "css/two.css";
     document.getElementsByTagName("head")[0].appendChild(ss);

}

AND so on

share|improve this answer
    
thank you, and does this have to be in the header? –  Cody Raspien Feb 18 '14 at 17:09
    
it has to be inside script tag <script></script> you can put the script tags inside head tag, or in body. I think better inside head tag @CodyRaspien –  AtanuCSE Feb 18 '14 at 17:13

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.