WebComponent setter not triggered if defer is used
I recently noticed that a setter in a web component is not being called when you inject the webcomponent javascript file with a script tag where the defer
attribute is used.
You can see the code here: https://codesandbox.io/s/web-component-with-setter-1ij4o
Within the script
tag of the index.html
, I set the property foobar
to "test". This should trigger the setter of the webcomponent, which should print the value "test" to the screen by an alert command. But this does not happen. If you delete the defer
attribute, everything works as expected. Can you tell me why this is happening, and do you have a solution where the setter is being called without deleting the defer
attribute?
What's happening is that your inline script is running before the deferred script.
You can solve this by either putting your inline script in a file and loading it with the defer attribute OR by putting the inline code inside an event listener to run after the 'DOMContentLoaded' event.
document.addEventListener('DOMContentLoaded', () => {
const wc = document.querySelector("custom-text");
wc.foobar = "test";
});