Tuesday, September 15, 2015

Web Components: no size in attachedCallback

When I made the upper88-wordclod web component everything worked fine when I had hard-coded sizes in the beginning. The library worked well and gave the ouput I expected (well, actually a bit better, it's an awesome library).

But when I switched to a size set with CSS it stopped working. After some debugging I realized that the element had no size yet. When attachedCallback(which is the place where you would render your element for the first time) is called, the element has no size set yet, so if your code (or a library you might use) relies on getting the height or width of the element ity won't work.

The recommended way is to remove all sizing from javascript and do it in CSS instead, which will work, but in my case that was not an option. Instead I had to add a call to setTimeout to make the actual rendering take place a bit later, after sizes have been calculated. That seems to work well, you don't actually see the delay and I have had no problem with the solution.

No comments: