簡體   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