Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing custom JavaScript on specific pages of the site from a single file

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?

like image 1000
zmol Avatar asked Feb 05 '11 03:02

zmol


People also ask

Can I use one js file for multiple HTML pages?

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.

How can you apply JavaScript to a web page?

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.

Can I run JavaScript before the whole page is loaded?

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.

Should I put all my JavaScript in one file?

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.


1 Answers

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
    • example: http://www.google.com/subdir/subpage.html
  • window.location.hostname - returns just the hostname (the domain name, including any subdomains)
    • example: www.google.com
  • 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 "#"))
    • example: /subdir/subpage.html

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>
like image 91
jhartz Avatar answered Sep 29 '22 07:09

jhartz