繁体   English   中英

我如何使File.js(Java脚本文件)执行并加载到特定页面中而不加载到其他页面中?

[英]how i make File.js (java script file) execute and loaded in a specific page and not loaded in other pages?

如何使Java脚本像只在首页中加载而在其他类别中不加载那样,请发布页面,因为它们没有滑块..所以我不需要它!

<script src='http://slideshow.googlecode.com/files/jquery-ui.min.js' type='text/javascript'/>

如果您不希望脚本加载到页面上,则不要包含它。 如果您的网站使用的是CMS,请发布您正在使用的CMS,以便我们为您提供帮助。

如果一切失败,则可以在body标签上设置类似ID的内容。 然后,您可以测试主体的ID,如果它通过了,则执行代码,如果它失败,则不要执行它。

- 编辑 -

一个例子就是这样。

<body id="home">
   <script language="JavaScript">
       function init() {
           if(document.getElementsByTagName('body')[0].id == 'home') {
               // We're grabbing the head and the script
               var headElement = document.getElementsByTagName('head')[0],
                   scriptElement = document.createElement('script');

               // We're setting the new script element to use the URL of the script we want
               scriptElement.type= 'text/javascript';
               scriptElement.src= 'http://slideshow.googlecode.com/files/jquery-ui.min.js';

               // We're adding this newly created element to the head
               headElement.appendChild(scriptElement);
           }
       }
       init();
   </script>
...
</body>

尝试类似的事情。 有关使用动态JavaScript元素的更多说明,请查看以下页面: http : //unixpapa.com/js/dyna.html

如果要在客户端控制此行为,请尝试以下方法:

<script>location.pathname == '/' && document.write('<script src="http://slideshow.googlecode.com/files/jquery-ui.min.js">\x3C/script>')</script>

但是,当然最好让CMS /服务器代码为您处理它。 但是根据您提供的信息,我只能为您提供客户端解决方案。

我相信您做错了什么,如果不需要脚本,请不要按照Tim的回答加载它。

无论如何,您都可以创建脚本yousrcipt.js包含在每个页面中。 在此脚本中,您可以编写类似以下内容

if (window.location == 'whateverhomepage')  {
   var head= document.getElementsByTagName('head')[0];
   var script= document.createElement('script');
   script.type= 'text/javascript';
   script.src= 'http://slideshow.googlecode.com/files/jquery-ui.min.js';
   head.appendChild(script);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM