Forced reflow violation and page offset - is it normal?

2.1k Views Asked by At

When adding a position: fixed on-scroll on my navbar the DOM throws the error: [Violation] Forced reflow while executing JavaScript took ms, on every scroll event. From my understanding (and Googling) this means there is layout thrashing everytime a scroll event happens due to new calculation.

My question is; is this a problem? I can't really crack the code of how to improve it to remove the violation, hence why I wanted to hear if this is 'standard' behaviour when working with scroll offsets.

The code I'm using is below:

document.addEventListener('DOMContentLoaded', function() {
    
  window.addEventListener('scroll', addPositionFixed);

  var navbar = document.getElementById("navbar");

  var sticky = navbar.offsetTop;

  function addPositionFixed() {
    if (window.pageYOffset >= sticky) {
      navbar.classList.add("sticky");
    } else {
      navbar.classList.remove("sticky");
    }
  }
})
1

There are 1 best solutions below

0
Dannie On

I found an answer that seemed to work and throw no errors:

window.onscroll = function() {myFunction()};

var header = document.getElementById("navbar");
var sticky = header.offsetTop;

function myFunction() {
  if (window.pageYOffset > sticky) {
    header.classList.add("sticky");
  } else {
    header.classList.remove("sticky");
  }
}

Atleast that does not throw any errors anymore!