4

I'm using justifiedGallery for my web page. When I visit the page at first time, the gallery appears correctly. But when I reload the page, it'll break.

enter image description here

I'm using meteor and react.

Old code sample:

$(document).ready(() => {
  $('#gallery').justifiedGallery({
    rowHeight: 400,
    fixedHeight: false,
    lastRow:   'justify',
    margins:   -3,
  });
});

I've put it to jQuery setTimeOut() function.

setTimeout(function(){
  $('#gallery').justifiedGallery({
    rowHeight: 400,
    fixedHeight: false,
    lastRow: 'justify',
    margins: -3,
  });
}, 100);

Now it's working fine. I just need to know that this is the correct way of fixing it? This is for the future proof.

1 Answers1

0

You should never run the code that manipulates DOM globally like that. What you're getting is a race condition with actual template rendering. This will sometimes randomly work, sometimes randomly not, and will always run into collisions with templating engine that will at best hinder the app performance.

Move the gallery creation to Template.onRendered() method and use this.$('.gallery') instead of just $('#gallery'). If you're using React, the equivalent place is componentDidMount method of the presentation component containing the .gallery div.


Side note: don't use ids for element selection, use classes or data attributes. Ids are a bad practice since the components you're creating are not reusable and may have performance issues.

Hubert OG
  • 19,314
  • 7
  • 45
  • 73