0

We are trying to minimize Forced Reflows which can be caused by stuff like getComputedStyle().

Our problem: Currently we are passing our CSS breakpoints to JavaScript by having an DOM element with the following styling:

.breakpoint {
  display: none;

  @media (min-width: $breakpoint-medium) {
    display: block;
  }

  @media (min-width: $breakpoint-large) {
    display: flex;
  }
}

Then in JS we check the display property with getComputedStyle() which causes a Forced Reflow.

Do you have an other way of passing the CSS breakpoints to JS without having the Forced Reflow?

Thank you!

Simon Knittel
  • 1,730
  • 3
  • 15
  • 24
  • Why not store the break-points in JS variables according CSS files as a constant type? Because you know already how many breakpoints you set. Or you need something else? – Hanif Feb 01 '18 at 13:46
  • That would be our workaround. We would really like to have a single source of truth. – Simon Knittel Feb 01 '18 at 16:35

2 Answers2

0

Add the following div to your html:

<body>
   ... your html here
   <div id="breakpoint"></div>
</body>

And add this to your SCSS:

#breakpoint{
   opacity: 0; //so you do not see it
   width: 1px; //so it works even with a 0 pixel canvas
   position: fixed; // so as not to change your page layout
      @media (max-width: $breakpoint-medium){
         display: none;
      }
   }
}

Then in javascript do the following:

var getCurrentBreakpoint = function(){
  return document.getElementById('breakpoint').offsetWidth > 0?'desktop':'tablet';
}
//getCurrentBreakpoint() = 'desktop' on desktop
//getCurrentBreakpoint() = 'tablet' on devices smaller than $breakpoint-medium

This answer works because the offsetWidth of an element returns 0 if that element is hidden in all browsers. See also this answer to an earlier question on 'How to check element's visibility via javascript?'.

What if I have more than two breakpoints?

If you have multiple breakpoints just create multiple divs, one for each breakpoint. Then make sure each breakpoint divs is only visible in one breakpoint range.

Tom
  • 233
  • 1
  • 6
0

You could set CSS breakpoints with JavaScript as well, by using the method insertRule().

Here is an example:

const css = window.document.styleSheets[0];
css.insertRule(`
  @media (min-width: 768px) {
    .breakpoint {
      display: none;
    }
  }
`, css.cssRules.length);
Reza Saadati
  • 5,018
  • 4
  • 27
  • 64