my js file loads on all pages. Some functions are meant to run only on certain pages like the homepage only http://site.com. Can javascript read the url of the page it’s being called from to determine if it’s the homepage?
my js file loads on all pages. Some functions are meant to run only
Share
You can use the window.location object to get properties about the location. Some notable properties are:
window.location.href– returns the entire URL of the current pagewindow.location.hostname– returns just the hostname (the domain name, including any subdomains)window.location.pathname– returns just the path (the part following the hostname/domain, but not including the query string (part of the URL that begins with a “?”) or the hash (part of the URL that begins with a “#”))Although all this works well, I would recommend (like others have mentioned) that it would be better to do this server-side. The server can usually do stuff like this better than the client.
Additionally, if you have all your JS code in a single central file, you could add something like this directly to the page (on the server) to trigger an event for just that page, which may be more reliable than JS location sniffing: