Ad/iklan :







Search.Pencarian Menu

Add text send email to rh3252705.adda@blogger.com or Click this (Text porn Will delete) | Tambah teks kirim email ke rh3252705.adda@blogger.com atau Klik ini (Teks porno akan dihapus)
Total post.pos : 13631+

[Go Make Things] My Web Component doesn't load when my JavaScript is in the header

I've been making a lot of YouTube videos about Web Components lately.

I generally like to do my instantiations in the constructor(). If you put stuff in the connectedCallback(), you can end up reinstantiating things over-and-over whenever an element is moved around the DOM.

customElements.define('my-library', class extends HTMLElement {  	constructor () {    		// Access parent properties  		super();    		// Find elements  		this.btn = this.querySelector('button');  		this.announce = this.querySelector('[role="status"]');    		// Listen for events  		this.btn.addEventListener('click', this);    	}    	// ...    });  

One of the more common issues I hear from folks, though, is…

Doing stuff in the constructor() throws an error when you load your JavaScript in the header.

To which I say… don't load your JavaScript in the header!

Or if you do, add the [defer] attribute. Or wrap your code in a DOMContentLoaded event listener. Or both.

This is true for any DOM manipulation script, by the way.

The Web Component example above will error when loaded in the header because when it runs, the elements inside the custom element might not be loaded into the DOM yet. Loading in the footer, or waiting until the DOM is ready, gets around that.

Cheers,
Chris

Want to share this with others or read it later? View it in a browser.

Share :

Facebook Twitter Google+
0 Komentar untuk "[Go Make Things] My Web Component doesn't load when my JavaScript is in the header"

Back To Top