senff / WordPress-Sticky-Block

1 stars 0 forks source link

JS optimization: Stop margin-top calculation once sticky block out of viewport #3

Open porg opened 1 year ago

porg commented 1 year ago

Page with this block setup

Performance

Performance without Sticky Block wrapper

Performance with the Sticky Block wrapper

As soon as the .wp-block-senff-sticky-block starts to get sticky it gets a CSS inline style like this:

position: fixed
left: …
top: …
width: …
margin-left: …
pading: …
margin-top: …
z-index: …

All values get initialized when the collision with the viewport top occurs first. And margin-top then gets constantly updated while scrolling.

Even when the object is long gone from the viewport.

Now when I have 10 column blocks on a page, each with a sticky image or image slider, I imagine the performance to degrade even more, as the JavaScript then needs to monitor and update more and more the further you scroll down.

I) Optimization potential

Is it maybe possible to set the sticky block back to its default CSS position value when it passed outside the viewport?

Possibly not so easy as when scrolling up you need to detect that too and update the value accordingly. So constantly updating margin-top sure was the easiest solution. But I doubt that it scales well performance wise for many objects in a page.

Idea: Create a lookup table like this:

scroll-position-y-axis ; object-to-reactivate ; margin-top
1240px ; #sticky-block-1 ; -240px
2240px ; #sticky-block-2 ; -1240px
...

If you scroll upwards and pass those scroll-position-y-axis treshhold values you re-activate the object-to-reactivate to its margin-top value again.

II) Other idea: Entirely different paradigm:

Only have 2 events:

  1. on page loading
  2. on viewport resizing

On these two events do this:

porg commented 7 months ago

Would appreciate that JS optimization!