this. In a traditional function
thisis bound to different values depending on the context it is called. With arrow functions, it is bound to the code that contains the arrow function. Because arrow functions also have syntax benefits, as a general rule, use arrow functions unless you need a more traditional treatment of
this(like in an event listener).
importstatements to break apart and reassemble your code into consumable chunks.
importstatements to load parts of an external library you may need for any given component. The code below will give you an example:
windowobject or the global namespace should be done carefully.
windowobject pollution can result in collisions with other scripts. We should wrap our scripts in closures and expose methods and properties to
iwas not exposed to the
someContentin the above example is
onerrorattribute will be executed.
textContentis safer than using
innerHTMLbecause it does not parse strings as HTML — meaning any malicious code passed to it will not be executed. Refer to MDN's documentation on
textContentfor more info.
document.createElementmethod to create new elements and the
ElementAPI to set attributes and append them to the document. Creating your own elements and attributes will ensure that only those you explicitly define will make their way into the DOM.
ElementAPI is the preferred best practice to safely create and add DOM elements. However, it tends to result in much more verbose code compared to HTML-parsing methods like
innerHTML. This can become painful if you need to dynamically create a large number of new elements. In these cases, the convenience of methods like
innerHTMLcan be extremely tempting.
DOMParserto parse and sanitize HTML strings before adding the HTML to the DOM with a method like
innerHTML. Parsing HTML strings with a
DOMParserwill not automatically make the code any safer, but it will allow you to access the elements from the string and strip potentially unsafe tags and attributes before they have a chance to get executed. Refer to MDN's documentation on
DOMParserfor more info.
innerHTML. However, no library is perfect, so be aware that you are relying on the security of the sanitizer you choose. Also, remember to consider the effect on performance when deciding whether to add any large library to your project.
<body>for all our events. Well, we want the event to bubble up the DOM as little as possible for performance reasons. This would also be pretty messy code to write.