用ejs&x27表达;s客户端javascript文件

用ejs&x27表达;s客户端javascript文件,javascript,node.js,express,templates,ejs,Javascript,Node.js,Express,Templates,Ejs,最近,我尝试使用express和ejs创建一个网站,我发现我不能对所有ejs(视图)文件只使用一个javascript文件,因为当我将DOM元素作为目标来执行某些操作时,如果其他视图页面没有该DOM元素,我的控制台将出错 示例: (因此,如果我访问索引页,我很好,但是当我在about页上时,我得到了一个错误,因为about页上不存在具有该类的元素) index.ejs <div class="main-container"> <h1 class="home-headin

最近,我尝试使用express和ejs创建一个网站,我发现我不能对所有ejs(视图)文件只使用一个javascript文件,因为当我将DOM元素作为目标来执行某些操作时,如果其他视图页面没有该DOM元素,我的控制台将出错

示例: (因此,如果我访问索引页,我很好,但是当我在about页上时,我得到了一个错误,因为about页上不存在具有该类的元素)

index.ejs

<div class="main-container">
    <h1 class="home-heading">Home page</h1>
    <p>some random text</p>
</div>
<%- include('../partials/header'); -%>
<h1>Hello world</h1>
<a href="/about" >about</a>
<% const currentPage = "index"; %>
<%- include('../partials/footer',{currentPage: currentPage}); -%>
所以我的问题是,链接客户端javascript文件的最佳方式是什么?我能想到的唯一方法是创建多个js文件,使每个ejs页面都有自己的js文件,这是最佳实践吗?或者有没有其他方法可以让我只用一个js文件就可以工作

现在我想说的是:

在查看页面(主页)上,我将创建一个值为index的变量,并传递到footer(部分)

index.ejs

<div class="main-container">
    <h1 class="home-heading">Home page</h1>
    <p>some random text</p>
</div>
<%- include('../partials/header'); -%>
<h1>Hello world</h1>
<a href="/about" >about</a>
<% const currentPage = "index"; %>
<%- include('../partials/footer',{currentPage: currentPage}); -%>

你好,世界
footer.ejs

  </div>
  <%- include('../partials/scriptFiles',{currentPage: currentPage}); -%>
 </body>
</html>

我将再次将变量向下传递到scriptFiles.ejs(partial),以检查我在哪个页面上,并使用正确的文件路径输出js标记

scriptFiles.ejs

<% let currentScriptFile = ''; %>

   <% if(currentPage === 'index'){ %>
      <% currentScriptFile = '<script src="./script.js"></script>'; %>
   <% }else if(currentPage === 'about') { ; %> 
      <% currentScriptFile = '<script src="./about.js"></script>'; %>
   <% } %>

<%- currentScriptFile %> //Output script tag with correct file path

//具有正确文件路径的输出脚本标记
所以,当我在主页上时,它将使用./script.js,当我在关于页面上时,它将使用./about.js,将express与ejs一起使用,这是正确的方法吗?如果不是,最好的方法或正确的方法是什么

谢谢

所以,如果我访问索引页面,我很好,但是当我在about页面上时,我得到了一个错误,因为about页面上不存在带有该类的元素

健壮地编写JavaScript,以便它能够处理这种状态

const duck = document.querySelector(".duck");
if (duck) {
    // The element exists and you can do stuff with it.
}