0

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>;
}
2
  • Does this answer your question? Call external java script files conditionally Commented Sep 11, 2022 at 23:06
  • That is not how you add scripts dynamically. You want createElement and appendChild Commented Sep 11, 2022 at 23:12

2 Answers 2

2

I think, we should to try to using

element.innerHTML = script

Into the if else area

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

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
0

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>

Comments

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.