I have a JavaScript function that should only run on specific pages on a website.
The function lives in a seperate script.js file that is shared between every page on the site.
To ensure that this function only runs on a specific page I currently hard code the onload attribute to the body tag on the pages that I want it to run e.g. <body onLoad="myFunction()">
I was contemplating removing this and instead adding some code to my function whereby it gets the current URL and if it matches one of the URL’s in a list of allowed URL’s then it will run.
Is it worth doing this or shall I retain the need to just add an onload attribute to each body tag?
Or is there a better solution to only run a function on specific pages?
Paul Irish has nice post on how to load scripts on needed pages, check out: