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?

2

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.