The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript When is it safe to run JS that needs to know layout?

  • This topic is empty.
Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
  • #284097

    I kinda thought I knew the answer to this until recently. I thought if you’ve got CSS linked in the head, and Javascript at the end of the document, then you were good. Then when using a script that resizes text, depending on container (Fitty), I started seeing a problem where the calculations were wrong. I initially opened an issue for Fitty. I then found that other scripts were doing similar things (with less dramatic results). Popper.js and Swiper were both getting calculations wrong (resizing the viewport in all cases would trigger a recalculation, fixing the discrepancy). This seems to be more of an issue in Firefox than other browsers.

    The only way I could get any of these scripts behaving reliably was to run them on window.onload. This feels a bit heavy handed, and also like it is fixing the problem by way of an arbitrary delay.

    I feel like there should be a way of saying “once the browser knows where everything is, run this”.


    If there are images that should be included in the calculations, window.onload is the way to go. It’s not really heavy handed, it actually meets the criterium of your last sentence – the browser will only know where everything is (or should be placed) once the images are loaded. Placing a script at the bottom of the page only makes sure the page markup itself is read.

    Of course onload isn’t bulletproof when the page uses async script calls but I suppose that isn’t the case here.


    I should have mentioned, the content does not determine the layout in any of the examples I am looking at. In the first example there are no images on the page, for both the Popper (the RSS icon), and Swiper examples, the layout is the same if loaded with images disabled.

    In all the examples there is either a CSS grid, a flex box, or an absolutely positioned element involved. So the question is more about CSS being loaded (and then, presumably, calculations done), rather than content. What if you don’t want to wait for images to load, but you do need the browser to have figured out a CSS grid for example (by figured out I mean, for example, know what a quarter of the viewport width, minus column gaps is)?

Viewing 3 posts - 1 through 3 (of 3 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.