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?
You can store one or more of your JavaScript scripts in a single . js file and access them from multiple HTML pages. Put the script in an external JavaScript file. If you have the script already inside your HTML page, remove all the JavaScript code inside the <script> tag and paste it into a separate file.
To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.
You can run javascript code at any time. AFAIK it is executed at the moment the browser reaches the <script> tag where it is in. But you cannot access elements that are not loaded yet.
To avoid multiple server requests, group your JavaScript files into one. Whatever you use for performance, try to minify JavaScript to improve the load time of the web page. If you are using single page application, then group all the scripts in a single file.
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 page
window.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:
<script type="text/javascript">
// jQuery example
$(document).ready(function () {
// Run function that is specific for this page
MyNamespace.initHome();
});
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With