从单个文件在网站的特定页面上执行自定义JavaScript [英] Executing custom JavaScript on specific pages of the site from a single file

查看:71
本文介绍了从单个文件在网站的特定页面上执行自定义JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的js文件在所有页面上加载.有些功能只能在某些页面上运行,例如首页http://site.com. javascript可以读取正在被调用的页面的URL以确定它是否是主页吗?

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?

推荐答案

您可以使用 window.location 对象以获取有关位置的属性.一些值得注意的属性是:

You can use the window.location object to get properties about the location. Some notable properties are:

  • window.location.href-返回当前页面的整个URL
    • window.location.href - returns the entire URL of the current page
      • example: http://www.google.com/subdir/subpage.html
      • 示例: www.google.com
      • 示例:/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.

      此外,如果您将所有JS代码存储在单个中央文件中,则可以将类似这样的内容直接添加到页面(在服务器上)以触发仅该页面的事件,这可能比JS位置更可靠嗅探:

      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>
      

      这篇关于从单个文件在网站的特定页面上执行自定义JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆