Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Position sticky

I know it's great that web developers can accomplish things like this now without js:

.sticky {
  position: -webkit-sticky;
  position: -moz-sticky;
  position: -ms-sticky;
  position: -o-sticky;
  top: 15px;
}

vs

<style>
.sticky {
  position: fixed;
  top: 0;
}
.header {
  width: 100%;
  background: #F6D565;
  padding: 25px 0;
}
</style>

<div class="header"></div>

<script>
var header = document.querySelector('.header');
var origOffsetY = header.offsetTop;

function onScroll(e) {
  window.scrollY >= origOffsetY ? header.classList.add('sticky') :
                                  header.classList.remove('sticky');
}

document.addEventListener('scroll', onScroll);
</script>

But under the hood of the actual browser isn't it doing the same kind of rendering, and take up the same amount of memory. In essence is there a lower level of code in the browser that renders the CSS finds the position: -webkit-sticky, and does somewhat of the same rendering as the javascript above?

like image 252
1337 Avatar asked Aug 14 '26 00:08

1337


1 Answers

In essence is there a lower level of code in the browser that renders the CSS finds the position: -webkit-sticky, and does somewhat of the same rendering as the javascript above?

No. The browser does not have to do the same thing.

With native support for sticky regions, for each clipped region the browser can maintain two separate graphics buffers -- one for non-sticky content which is sized to the container and one for sticky content which is sized to the viewport. On scroll, it

  1. grabs the visible region of the first,
  2. composite that with the second (taking into account z-indices)
  3. blits that to the screen.

The browser does not need to deal with the DOM at all.

Compare that to the JS onscroll approach.

  1. grab a lock in case JS from another frame is currently computing something in the current frame
  2. set up a JS execution context
  3. run the user function
  4. check whether any CSS selectors need to be re-applied
  5. check whether the DOM needs to be laid out
  6. check whether DOM modification event listeners need to be fired
  7. figure out which bits of the DOM need to be re-rendered -- this isn't a matter of moving around rectangles that have already been rendered
  8. re-render
  9. composite
  10. blit
like image 195
Mike Samuel Avatar answered Aug 16 '26 14:08

Mike Samuel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!