Blog2016 ≫ Sped up the site with javascript event delegation

Just rewrote some code that I've been running on here for about ten years, sweet titles, originally this1, but I tweaked it over time. now I've rewritten it2 (minfied version here) and it's small and fast. And I just realised I can improve it further still.

The original version was amazing, and was written ten years ago...

Instead of adding an event for every link on the page, to pop open the purple tooltip when you hover over it, I have one event on the whole page that says "what element am I over? Is it a link? Should it have a tooltip? Ok let's show it". Simple stuff I should have done a long time ago, but good to have it now. Means I get a better score here3 by having less events added to the dom when the page loads. This means the page is quicker for the user.

The tech difference is basically, old code:

document.getElementsByTagName('A').forEach(function(element) {
  element.addEventListener('[mouse](/wiki/#mouse)over', function (event) {
    // do our thing when someone hovers over a link
  })
})

new code:

document.addEventListener('[mouse](/wiki/#mouse)over', function (event) {
  if (event.target == 'A') {
    // do our thing when someone hovers over a link
  }
})

The result is the same but we have only attached one event to the page, that will be triggered on every link, rather than attaching an event to every link.

This also means that new elements that get injected into the page will automatically get the tooltips - you won't see many of these but I do, so this site is quicker for me to use too. And I'm the only person really using this site so that's what matters... anyway because new elements get these new superpowers automatically, I never have to run the script again, so I don't have to export the ability to run the script again from the file, so I can keep it even smaller and even more self contained. That's the next step, it might go down in size again by 50%.

⬅️ :: ➡️

Paul Clarke's weblog - I live in A small town, Kent. Married to Clare + dad to two, I'm a full-stack web engineer, + I do javascript / nodejs, some ruby, python, php ect ect. I like pubbing, parkrun, eating, home-automation and other diy jiggery-pokery, history, family tree stuff, TV, squirrels, pirates, lego, and TIME TRAVEL.