Home > Software design >  How to call different scripts based on url using if els statement
How to call different scripts based on url using if els statement

Time:09-12

How can I run a specific .js script if url matches "/search" or run a different .js script if the url is different using if/else statement? This would go in head section and either are used to build the DOM based on the url.

Would the code below work? Any help appreciated!

if (window.location.pathname === '/search') {
  <script type="text/javascript" src="file1.js"></script>;
}
else {
  <script type="text/javascript" src="file2.js"></script>;
}

CodePudding user response:

I think, we should to try to using

element.innerHTML = script

Into the if else area

CodePudding user response:

During the page loading phase, you could use document.write.

<script>
document.write(window.location.pathname === '/search' ? 
    '<script type="text/javascript" src="file1.js"><\/script>' :
    '<script type="text/javascript" src="file2.js"><\/script>');
</script>
  • Related