3

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?

Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
Cody Raspien
  • 1,753
  • 5
  • 26
  • 51
  • here's an example http://stackoverflow.com/a/577002/1113766 – Juan Feb 18 '14 at 17:05
  • possible duplicate of [How to load up CSS files using Javascript?](http://stackoverflow.com/questions/574944/how-to-load-up-css-files-using-javascript) – apaul Feb 19 '14 at 02:08

1 Answers1

3
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

AtanuCSE
  • 8,832
  • 14
  • 74
  • 112
  • it has to be inside script tag `` 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