From d9af8199e6064459952e97426703ed3f5fa99569 Mon Sep 17 00:00:00 2001 From: Andrew Bagshaw Date: Tue, 5 Dec 2017 13:07:58 -0800 Subject: [PATCH] Switch to ResizeObserver from window onresize --- package.json | 2 ++ src/salieo.js | 29 ++++++++++++++++++++++------- 2 files changed, 24 insertions(+), 7 deletions(-) diff --git a/package.json b/package.json index 872db44..c835993 100644 --- a/package.json +++ b/package.json @@ -10,10 +10,12 @@ "devDependencies": { "browserify": "^14.5.0", "cropcalc-js": "^0.9.3", + "debounce": "^1.1.0", "mkdirp": "^0.5.1", "pixelmatch": "^4.0.2", "pngjs": "^3.3.1", "puppeteer": "^0.13.0", + "resize-observer-polyfill": "^1.5.0", "tap-spec": "^4.1.1", "tape": "^4.8.0", "uglify-js": "^3.2.1" diff --git a/src/salieo.js b/src/salieo.js index 013a8c6..e8bb166 100644 --- a/src/salieo.js +++ b/src/salieo.js @@ -1,8 +1,13 @@ var cropcalcJS = require("cropcalc-js"); +var debounce = require("debounce"); +var ResizeObserverPolyfill = require("resize-observer-polyfill"); + +var ResizeObserver = ResizeObserver ? ResizeObserver : ResizeObserverPolyfill; function salieo(userOptions) { var loadedImages = []; var salieoDataCache = {}; + var ro; var options = { img_class: "salieo", @@ -18,15 +23,13 @@ function salieo(userOptions) { window.addEventListener("message", triggerEditMode); } - setOpts(options, userOptions); - refresh(); - if(options.watch_resize) { - window.addEventListener('resize', function(event) { - refresh(); - }); + ro = new ResizeObserver(debounce(refresh, 10)); } + setOpts(options, userOptions); + refresh(); + //Handy to use functions function setOpts(standard, user) { if (typeof user === 'object') { @@ -264,6 +267,10 @@ function salieo(userOptions) { } function refresh() { + if(ro) { + ro.disconnect(); + } + var rawElements = document.getElementsByClassName(options.img_class); var newSalieoDataCache = {}; var tmpImgInfo, currentImage; @@ -271,6 +278,10 @@ function salieo(userOptions) { loadedImages = []; for(var i = 0; i < rawElements.length; i++) { + if(ro) { + ro.observe(rawElements[i]); + } + tmpImgInfo = getElementURL(rawElements[i]); if(!tmpImgInfo) { continue; //Error getting image URL @@ -298,11 +309,15 @@ function salieo(userOptions) { var avoidElements = document.getElementsByClassName(options.avoid_class); var avoidAreas = []; for(var i = 0; i < avoidElements.length; i++) { + if(ro) { + ro.observe(avoidElements[i]); + } + avoidAreas.push({elementRect: avoidElements[i].getBoundingClientRect(), dataset: avoidElements[i].dataset}); } var tmpElementRect; - for(var i = 0; i < loadedImages.length; i++) { + for(var i = 0; i < loadedImages.length; i++) { loadedImages[i].elementRect = loadedImages[i].element.getBoundingClientRect(); loadedImages[i].cropOptions = Object.create(options.crop_options);