Beginner’s JS – Week 3 & 4
Browser Performance & Repaints
An example of a repaint might look something like this next example, where we Add a child to the DOM (repaint 1), then add a new paragraph (repaint 2), then we add a new image (repaint 3), which forces the browser to repaint upwards of three times, which is no good:
// Add a div with a paragraph and image inside of it to the DOM document.body.appendChild(myDiv); myDiv.appendChild(myParagraph); myDiv.appendChild(myImage);
// Only one paint since we add to the DOM once at the end myDiv.appendChild(myParagraph); myDiv.appendChild(myImage); document.body.appendChild(myDiv);
Speaking of placing content into the DOM
One of the coolest parts of these sections was the introduction of a new ability in ES6 I haven’t been exposed to before called the `.insertAdjacentElement()` API. It is super slick for letting you control where you want elements to be inserted, allowing you to insert the before the target, inside the target at the top, inside the target at the bottom, or after the target. This simplifies things greatly compared to simply `.append()` or `.appendChild()` and gives us a lot more accuracy.
Another small takeaway
In the final “DOM Cardio” section of the fourth module, Wes mentions in passing the existence of something which blew my mind. In the course you’re tasked with creating a button on a series of cards and if the button is ever pressed it removes the card it’s within. The task is simple enough and illustrates some core principles that had been covered in the course leading up to this point, but the part which fascinated me is how the function is able to find which button was pressed (and therefore which card to delete).
For context, in the past we’d often need to set up a lot of information to then pass into functions before you could run them, so if we needed to find which “card” to delete, we’d first have to identify which button was pressed and then pass its specific button element information into the function as an argument so that the function could accurately make adjustments to the correct button that was pressed.
TURNS OUT that you can just call
event.currentTarget inside of the function and it returns to you the element which triggered the
eventListener, so there’s no need for complicated argument passing or anything, you can simply say “hey function, what was your target?” and the function just knows that implicitly and you can move on with your day without being all sweaty and clogging up your code with frivolous arguments. This might seem like a super small thing (and as a full disclaimer: I have no idea how long