$ is undefined

One of the most horrifying things that happened to me turned out to be a good lesson instead. Working on huge websites most of the time means that all kind of plugins, like jQuery, are provided by default. Also on my latest project, proactive chat, we were quite sure that the site uses jQuery.

quite sure jquery was loaded

Nevertheless we stumbled upon the error “$ is undefined”. The root cause of it was that the script we had was being executed before jQuery was loaded. Normally I would say, just include the script after jQuery has been initiated but in this case this was not possible.

Then I started thinking of a presentation I have been to by Remy Sharp, “I know jQuery. Now what?” He spoke about not using jQuery, and ever since the Mobilism event I have kept in mind that, at least for input fields:

$(this).val() === this.value

This inspired me to not see it as a problem but as a challenge to get rid of jQuery for this problem.

It turned out not to be very difficult since all we did was just getting a selector and kick off some functions. So this:

var selector = $('.ourSelector');
selector.on('change', function () {
    // do stuff

became this:

var selector = document.querySelector('.ourSelector');
selector.onchange  = function () {
    // do stuff

One thing Remy did is creating a substitute for the $ and on method. We decided not to, because that might have just leaded to other unforeseen problems with the rest of the site.