I am building a module to handle admin notifications in WordPress. It includes a script to perform an AJAX call when a notification is dismissed or collapsed. Since I’m adding an event listener, I need to wait until the page is loaded. My code looks like this, it is inlined after common.js so it’s being inserted in the footer:
jQuery(function() {
var dismissButton = document.querySelector("#my-notice-id .notice-dismiss");
dismissButton.addEventListener("click", async function(event){
await fetch("url", {
// etc etc etc
});
});
});
This seems to work reliably, but I’m hoping to replace the jQuery .ready with vanilla JS, and I’ve read that I can use DOMContentLoaded or load events, so replacing the first line with something like:
addEventListener("DOMContentLoaded", (event) => {
However, this often (but not always) results in the following error on the line with the interior click event listener:
Cannot read properties of null (reading 'addEventListener')
In other words, my querySelector is returning null in this case. Specifically, it seems to happen in the case of a soft reload. Everything works correctly if I hold shift while pressing reload in the browser.
The first thing I tried was to use the load event instead, but I’m told this can be undesirable because it doesn’t trigger until nearly everything is loaded, and I think that waiting for the DOM should be sufficient? This did not fix the issue.
jQuery documentation states that the main difference between this function and DOMContentLoaded is that a function on .ready will fire even if the DOMContentLoaded event has already fired… but it doesn’t seem like that would cause this? If my code wasn’t executing for this reason, I would think nothing would be executing at all.
In addition, I’m concerned that .ready only seems to work for some incidental reason, and the last thing I want is flaky code. Any assistance is greatly appreciated.
MalIlluminated is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.