Skip to content

Commit

Permalink
Merge pull request #373 from abettadapur/alebet/cache-width
Browse files Browse the repository at this point in the history
Cache the scrollbar width for the life of the application
  • Loading branch information
Grsmto authored Sep 25, 2019
2 parents b2c27f6 + d73ae26 commit 708e6ca
Showing 1 changed file with 28 additions and 14 deletions.
42 changes: 28 additions & 14 deletions packages/simplebar/src/scrollbar-width.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,36 @@
export default function scrollbarWidth() {
if (typeof document === 'undefined') {
return 0;
let scrollbarWidth = null;
let devicePixelRatio = null;

window.addEventListener('resize', () => {
if (devicePixelRatio !== window.devicePixelRatio) {
devicePixelRatio = window.devicePixelRatio;
scrollbarWidth = null;
}
});

const body = document.body;
const box = document.createElement('div');
const boxStyle = box.style;
export default function scrollbarWidth() {
if (scrollbarWidth == null) {
if (typeof document === 'undefined') {
scrollbarWidth = 0;
return scrollbarWidth;
}

boxStyle.position = 'fixed';
boxStyle.left = 0;
boxStyle.visibility = 'hidden';
boxStyle.overflowY = 'scroll';
const body = document.body;
const box = document.createElement('div');
const boxStyle = box.style;

body.appendChild(box);
boxStyle.position = 'fixed';
boxStyle.left = 0;
boxStyle.visibility = 'hidden';
boxStyle.overflowY = 'scroll';

const width = box.getBoundingClientRect().right;
body.appendChild(box);

body.removeChild(box);
const width = box.getBoundingClientRect().right;

return width;
body.removeChild(box);

scrollbarWidth = width;
}
return scrollbarWidth;
}

0 comments on commit 708e6ca

Please sign in to comment.