Roots Discourse

Masonry JS does not draw on page load with 'npm start' (OK after build:production)

I’ve included DeSandro’s Masonry Layout and ImagesLoaded in my project based on Sage 9.

Things are working fine after npm run build:production but not when the env is running with npm start.

var Masonry = require('masonry-layout');
var imagesLoaded = require('imagesLoaded');

export default {
  init() {},
  finalize() {
    var msnry = new Masonry('#posts-container', {
      itemSelector: '.grid-item',
      gutter: 10,
    }); // does not draw

    imagesLoaded(document.querySelector('#posts-container'), function () {
      console.log({ msnry }); // seen OK in console
      msnry.layout(); // yet does not draw
    });

    // test click event listener after page load
    document.querySelector('h1').addEventListener('click', () => {
      msnry.layout(); // draws
    });
  },
};

Any thoughts as to what might be causing this and how the problem could be avoided?

Usually when things work on build but not start it has to do with Hot Module Replacement (HMR). Sage 9 uses HMR so that styles, etc, can be updated in the browser while start is running without reloading the page. It’s a cool feature! But because it “reloads” content by directly modifying the DOM, it sometimes doesn’t trigger particular document events that other things might be expecting (i.e. onload) or it triggers them at the wrong time (i.e. before things have actually loaded).

I haven’t tested this out myself, but this post has a quick fix to disable HMR and BrowserSync, so start will still watch and rebuild your assets, you just have to reload the page in your browser manually: Is it possible to "watch" without browsersync?

Alternatively, you could refactor your code to trigger off of some other event that isn’t tied to document load (this is probably why msnry.layout() works when triggers off the click in your code).

Thanks for your response @alwaysblank! The linked modification to disable HMR / BrowserSync indeed does help in the situation I had.

Moreover, I’ve earlier experienced some “reload loop” issues with HMR (BrowserSync keeps reloading infinitely upon JavaScript changes), where the same mod may help, so it’s good have it readily available should a need arise.

This topic was automatically closed after 42 days. New replies are no longer allowed.