Load script in html based on cookie

2.2k Views Asked by At

How can I load scripts in a html based on the cookie value. I need to switch between development and deployment mode.

I am using wro4j but I can't find where the error comes in that wro4j grouped js files.

<head>

if (getcookie(debug-mode) load the following scripts

<script type="text/javascript" src="/assets/v/{{ASSET_VERSION}}/main-core.js"></script>
<script type="text/javascript" src="/assets/v/{{ASSET_VERSION}}/angular-core.js"></script>
<script type="text/javascript" src="/assets/v/{{ASSET_VERSION}}/angular-app.js"></script>

else load this script

<script type="text/javascript">
    loadIndividualJsCssFiles('config/assets.xml');
</script>
</head>

how to acheive this

1

There are 1 best solutions below

2
On

document.cookie is a string in the browser that contains all of your cookie information. A quick and dirty solution might look something like this:

function injectScript(src) {
    var script = document.createElement('script');
    script.src = src;
    script.type = 'text/javascript';
    document.body.appendChild(script);
}

if ( document.cookie.indexOf('debug-mode') > -1 ) {
    injectScript("/assets/v/{{ASSET_VERSION}}/main-core.js");
    injectScript("/assets/v/{{ASSET_VERSION}}/angular-core.js");
    injectScript("/assets/v/{{ASSET_VERSION}}/angular-app.js");

} else {
    var el = document.createElement('script');
    script.type = 'text/javascript';
    script.text = 'loadIndividualJsCssFiles(\'config/assets.xml\');';
    document.head.appendChild(el)
}

Note: I haven't tested this myself

Basically you are just looking for an occurance of the name of the cookie you are looking for within the document.cookie string.

A more robust approach might include converting your cookie string into key-value array.