Express with ejs's client side javascript file

Issue

recently I am trying to create a website using express and ejs and I found out that I can not just use one javascript file for all my ejs (view) files because when I target a DOM element to do something and if other view pages doesn’t have that DOM element I’ll get a error in my console.

Example:
(So if am visiting index page, I am fine but when I am on about page I got an error because that element with that class doesn’t exist on the about page)

index.ejs

<div class="main-container">
    <h1 class="home-heading">Home page</h1>
    <p>some random text</p>
</div>

about.ejs

<div class="main-container">
    <h1 class="about-heading">About page</h1>
    <p>some random text</p>
</div>

script.js

const homeHeading = document.querySelector('.home-heading');
homeHeading.style.backgroundColor = 'red'; 

So my question is what is a best way to link client side javascript file? The only way I can think of is creating multiple js files and make it so each ejs page has its own js file, is this best practice? or is there any other ways I can make it work using just one js file?

Right now this is what I came up:

on view page(home), I’ll create a variable with value of index and pass down to footer(partial)

index.ejs

<%- 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>

and I’ll pass the variable down again to scriptFiles.ejs(partial) to check which page I am on and output that js tag with correct file path

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

so when I am on home page it will use ./script.js and when I am on about page it will use ./about.js, to use express with ejs is this a correct way to do it? if not what is the best way or correct way to do it.

Thanks

Solution

So if am visiting index page, I am fine but when I am on about page I got an error because that element with that class doesn’t exist on the about page

Write the JavaScript robustly so it can cope with that state.

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

Answered By – Quentin

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published