roots / sage

WordPress starter theme with Laravel Blade components and templates, Tailwind CSS, and a modern development workflow
https://roots.io/sage/
MIT License
12.71k stars 3.06k forks source link

:wrench: Wait for CSS to be loaded before init JS #3100

Closed Striffly closed 1 year ago

Striffly commented 1 year ago

In development, CSS is injected and not included via a file. To be able to use correctly some JS functions that depend on style (el.scrollWidth, etc.), we have to wait until the CSS is injected and parsed.

kellymears commented 1 year ago

Wouldn't this cause issues with hot module reloading subsequent changes? The load event listener is not going to fire when a module changes, so it will only be called once.

I would think something like this might be preferable, as it will allow main code to execute on reload but also gives you a place to put code sensitive to onload:

import domReady from '@roots/sage/client/dom-ready';

/**
 * Application entrypoint
 */
domReady(async () => {
  window.addEventListener(`load`, () => {
    // css initialization
  })

  // normal app code
});

/**
 * @see {@link https://webpack.js.org/api/hot-module-replacement/}
 */
if (import.meta.webpackHot) import.meta.webpackHot.accept(console.error);

Not sure if this should be boilerplate. I'm thinking this is best handled as an app concern, as is. @retlehs, thoughts?

retlehs commented 1 year ago

Agree with handling it from the theme as needed — made a note to my docs backlog to account for @kellymears' comment