Search code examples
javascriptjqueryaddeventlistenerdomcontentloaded

$ is not defined before DOMContentLoaded - JQuery


the first statement in a js file I have is

$(document).on("DOMContentLoaded", function (event) {
   $(document.body).on('beforeinsert', onBeforeInsert);
   $(document.body).on('afterinsert', onAfterInsert);
   $(document.body).on('wait', onWait);
   $(window).on('load', onLoad);
});

but when I use firebug it tells me that "$ is not defined". Elsewhere in the file everything works as expected. In fact if I change the first line to

document.addEventListener("DOMContentLoaded", function (event) {

everything also works fine. I don't want to do this because I want to be able to get cross browser compatibility.


Solution

  • You're getting that error message because your script runs before $ is defined.

    To fix it, make sure jQuery is loaded before running that script.