从单个文件在网站的特定页面上执行自定义 JavaScript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4904921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Executing custom JavaScript on specific pages of the site from a single file
提问by zmol
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?
我的 js 文件加载到所有页面上。某些功能只能在某些页面上运行,例如仅在主页上运行http://site.com。javascript 可以读取调用它的页面的 url 以确定它是否是主页吗?
回答by jhartz
You can use the window.locationobject to get properties about the location. Some notable properties are:
您可以使用window.location对象来获取有关位置的属性。一些值得注意的属性是:
window.location.href- returns the entire URL of the current pagewindow.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
window.location.href- 返回当前页面的整个 URLwindow.location.hostname- 仅返回主机名(域名,包括任何子域)- 例如:www.google.com
window.location.pathname- 仅返回路径(主机名/域之后的部分,但不包括查询字符串(以“?”开头的 URL 部分)或哈希(以“#”开头的 URL 部分))- 示例:/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:
此外,如果您将所有 JS 代码放在一个中央文件中,您可以将类似这样的内容直接添加到页面(在服务器上)以触发该页面的事件,这可能比 JS 位置嗅探更可靠:
<script type="text/javascript">
// jQuery example
$(document).ready(function () {
// Run function that is specific for this page
MyNamespace.initHome();
});
</script>
回答by Phrogz
Put a unique idattribute 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:
id在<body>每个页面的元素上放置一个唯一的属性,并使用它来确定您的 JS 应该做什么。这就是我用我的单个缩小文件所做的,它(一旦它连接了许多较小的 JS 文件)看起来基本上像:
jQuery(function($){
if (!$('body#home').length) return;
//... code specific to the home page
});
jQuery(function($){
if (!$('body#contact').length) return;
//... code specific to the contact page
});
// etc. for each page
But you can just as easily write a more efficient single file as:
但是您可以像编写更高效的单个文件一样轻松:
jQuery(function($){
if ($('body#home').length){
//... code specific to the home page
}
if ($('body#contact').length){
//... code specific to the contact page
}
});
回答by Nimrod
Keep all of your JS code in a single file, let it load on every page (cached anyways) but here's the catch:
将所有 JS 代码保存在一个文件中,让它在每个页面上加载(无论如何都缓存),但这里有一个问题:
ONLYcall 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.
试图在 JS 文件中放置“我在哪个页面上”的逻辑似乎是倒退。
回答by Matti Virkkunen
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.
我认为在服务器端解决这个问题并根据页面调用正确的函数/加载正确的脚本可能是一个更好的主意。服务器端通常更清楚当前页面的用途。
回答by Jonathon Faust
You couldread 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.
您可以像 ClosureCowboy 所说的那样阅读 URL ,但这有点倒退。通常,如果您知道不需要 JavaScript 文件,则不会将其包含在页面中。
回答by David Duggins
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.
这是我用来为每个页面设置唯一 cookie 的一小段代码。它应该可以很好地获得您想要的东西。你可以通过一个开关运行它来为不同的页面产生不同的动作,或者只使用一个简单的 if 语句只在主页上运行代码。
var sPath = window.location.pathname;
var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
console.log(sPath);
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.
我添加了 console.log 以便您可以看到它在 Firebug 控制台中调用的页面。如果您希望它弹出,请将其更改为警报。
回答by ClosureCowboy
Your JavaScript can get the current URL using window.location.
您的 JavaScript 可以使用window.location.
alert(window.location);

