This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the javascript category.
Last Updated: 2024-11-21
I once had the following code called on every page of a website:
document.addEventListener('DOMContentLoaded', function () {
emailSubscribeForm = document.getElementById("new_email_subscriber")
// Don't worry about what this exact event does.
emailSubscribeForm.addEventListener('ajax:beforeSend', trackConversionAddEmail)
})
This code worked fine initially, since every page on the website contained the
new_email_subscriber
form. But the website evolved, and eventually had pages
without this element. This caused a JavaScript error.
This could be resolved with a quick nil check:
emailSubscribeForm && emailSubscribeForm.addEventListener('ajax:beforeSend', trackConversionAddEmail)
// OR: You might create a function that adds an event listener to an element
// only if it is present.
Never assume (in your JavaScript) that a DOM element is available on every page. Always entertain the thought that it is missing, and ensure your code gracefully handles this case.