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?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- How to fix IE ClearType + jQuery opacity problem i
- void before promise syntax
- jQuery add and remove delay
I think it might be a better idea to figure this out on the server side and call the correct functions/load the correct scripts depending on the page. The server side usually knows better what the current page is for anyways.
Here is a little piece of code that I have used to set a unique cookie for each page. It should work just fine to get exactly what you want. You can run it through a switch to produce different actions for different pages, or just use a simple if statement to run code only on the home page.
I added the console.log so that you can see what it calls the page in the Firebug Console. Change it to alert if you would rather it pop up.
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:
You could read the URL as ClosureCowboy said, but that's kind of backwards. Usually, if you know you don't need a JavaScript file, you don't include it on the page.
Keep all of your JS code in a single file, let it load on every page (cached anyways) but here's the catch:
ONLY call the functions you need from the page that needs them
Trying to put "what page am I on" logic in the JS file just seems backwards.
Put a unique
id
attribute on the<body>
element for each page, and use that to determine what your JS should do. This is what I do with my single minified file, which (once it concatenates many smaller JS files) looks basically like:But you can just as easily write a more efficient single file as: