I have two web pages. They share the same .js file, but the file contains code that I only want to execute for one or the other of the pages.
I thought I could handle it like below, where each page has an element with a unique id, either "page_1" or "page_2". The js then tests for the existence of this element before executing the code.
However, on page_1, even though it doesn't actually execute the code inside the page_2 IF statement, the function runStartFunction() is still overridden because it is defined twice.
How can I avoid this? Obviously I could give all the functions different names, but I have a lot of pages and I could accidentally use the same name at some point.
if (document.getElementById("page_1") != null){
alert("Page 1"); // executed, as expected
function runStartFunction(){
alert("what I want"); // not executed, but should be
}
}
if (document.getElementById("page_2") != null){
alert("Page 2"); // not executed, as expected
function runStartFunction(){
alert("what I don't want"); // executed, but shouldn't be
}
}
runStartFunction();