只在特定页面上执行js的最佳方式

Best way to execute js only on specific page

本文关键字:js 执行 最佳 方式      更新时间:2023-09-26

我想知道只在特定页面上执行java脚本代码的最佳方式是什么。

让我们想象一下,我们有一个基于模板的网站,重写内容列表集的规则,jquery可用,它基本上看起来是这样的:

  <!DOCTYPE html>
  <html>
   <head>
    <script src="script.js"></script>
   </head>
   <body>
    ...
    include $content;
    ..
   </body>
</html>

内容"信息"包含一个按钮,我们希望在点击时发生一些事情,当您悬停在文本字段时,内容"警报"应该会给我们一条消息。

在不因找不到对象而发生错误的情况下,触发这些操作的最佳方法是什么

选项一:使用window.location.pathname

 $(document).ready(function() {
      if (window.location.pathname == '/info.php') {
          $("#button1").click(function(){
            //do something
          })
      }else if(window.location.pathname == '/alert.php'){
           $("#mytextfield").hover(){
             alert('message');
           }
    }

选项二:检查元素是否存在

$(document).ready(function() {
  if ($("#button1").length > 0) {
      $("#button1").click(function(){
        //do something
      })
  }else if ($("#mytextfield").length > 0){
       $("#mytextfield").hover(){
         alert('message');
       }
}

选项三:在加载的模板中包含脚本

//stands for itself

有更好的解决方案吗?还是我必须接受其中一种解决方案?

感谢您的经验、用法或与本主题相关的任何链接。

//编辑:

我可能选择了一个糟糕的例子,实际的代码应该是这样的:

    mCanvas = $("#jsonCanvas");
    mMyPicture = new myPicture (mCanvas);

其中myPicture构造函数获取画布元素的上下文,如果mCanvas未定义,则抛出错误。

为body标记设置一个class属性。

<body class="PageType">

然后在你的剧本里。。

$(function(){
  if($('body').is('.PageType')){
    //add dynamic script tag  using createElement()
    OR
    //call specific functions
  }
});

我会使用switch语句和一个变量。(我在用jQuery!)

var windowLoc = $(location).attr('pathname'); //jquery format to get window.location.pathname
switch(windowLoc){      
  case "/info.php":
    //code here
    break;
  case "/alert.php":
    //code here
    break;
}
//use windowLoc as necessary elsewhere

这将允许你根据你所在的页面更改"按钮"的作用。如果我正确理解你的问题;这就是我要做的。此外,如果我提供了大量的javascript,我只需要完全添加一个新的JS文件。

var windowLoc = $(location).attr('pathname'); //jquery format to get window.location.pathname
switch(windowLoc){      
  case "/info.php":
    var infoJS = document.createElement('script');
    infoJS.type = 'text/javascript';
    infoJS.src = 'location/to/my/info_file.js';
    $('body').append(infoJs);
    break;
  case "/alert.php":
    var alertJS = document.createElement('script');
    alertJS.type = 'text/javascript';
    alertJS.src = 'location/to/my/alert_file.js';
    $('body').append(alertJs);
    break;
}

希望这有帮助-

干杯。

与检查URL路径有点不同的方法:您可以在一个函数中对页面特定的事件处理程序进行分组,然后在每个include中都有一个domready,它将调用这些函数。

例如:在script.js中,有两个函数(在domready之外),即onPage1Load()onPage2Load()

page1.php中,您有一个$(document).ready(onPage1Load)对于其他页面,依此类推。这将确保未注册意外事件处理程序。

您也可以使用vanilla javascript来执行相同的

console.log(window.location.href);
const host = "http://127.0.0.1:5500/";
// JAVASCRIPT FOR INDEX PAGE 
if (window.location.href == host + 'index.html') {
    console.log("this is index page");
}
// JAVASCRIPT FOR ORDER PAGE 
if (window.location.href == host + 'order.html') {
    console.log("this is order page");
}

您可以使用RequireJS(RequireJS是一个JavaScript文件和模块加载器)并在需要时加载脚本。链接是http://requirejs.org/,我知道使用require-js并不是那么容易。