Skip to content
Advertisement

How to dynamically load the URLs in an HTML head tag?

I’m trying to load my CSS and JS files based on a localStorage variable.

It looks just like this:

let jx = localStorage.getItem('jurisdiction');

document.write(`

<link rel="stylesheet" href="../_externals/stylesheets/assist/${jx}.css">
    
 `);

However this doesn’t seem to work and I can’t find a solution how to dynamically change a URL in the head tag.

I’d appreciate any help as to how to go about this. Thank you!

Advertisement

Answer

I think that href in your tag should look like this: href=../_externals/stylesheets/assist/${jx}.css

Notice that I have used template literals(“) to wrap the link in ‘href’ attribute. In order to use the ${jx} inside your link, you need to wrap the whole link inside the template literals(e.g. text${jsVariables}). I think this should work.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement