javascript - Is it possible to detect repaint/reflow in the browser? -


not sure if there solution problem. want know if there way detect when browser actually updates ui.

lets want add class element before run long-running, synchronous block of code, after synchronous function runs, class removed.

el.classlist.add('waiting'); longrunningsynchronoustask(); el.classlist.remove('waiting'); 

if run code, long running task started, , block ui before class added. tried using mutationobserver's, , checking element getcomputedstyle, doesn't work because don't reflect when realtime updates ui.

using worker might best solution (drop long running code in worker , post message when it's complete remove class). isn't option me, due needing support older browsers.

the solution works outside of implementing worker using settimeout. i'd love know if has run problem , if there way detect repaint/reflow of ui in browser.

see example better illustration of problem.

const el = document.queryselector('.target');  const isred = c => c === 'red' || 'rgb(255, 0, 0)';    let classactuallyapplied = false;    let requestid;    const longrunningtask = (mil, oncomplete) => {    if (classactuallyapplied) {      cancelanimationframe(requestid);      var start = new date().gettime();      while (new date().gettime() < start + mil);      oncomplete();    } else {       requestid = requestanimationframe(longrunningtask.bind(null, mil, oncomplete));    }  }    const observer = new mutationobserver(function(mutations) {  	classactuallyapplied = mutations    	.filter(mutation => {  			return mutation.type === 'attributes' &&        	mutation.attributename === 'class' &&          mutation.target.classlist.contains('waiting');  		}).length > 0;  });    const observerconfig = {  	attributes: true,   	childlist: false,   	characterdata: false   };    observer.observe(el, observerconfig);    el.addeventlistener('click', e => {  	el.classlist.add('waiting');    longrunningtask(1000 * 5, () => {    	// el.classlist.remove('waiting');    });  });
.target {    height: 100px;    width: 100px;    background-color: gray;  }    .waiting {    background-color: red;  }
<div class="target">    target  </div>

i believe requestidlecallback looking for.

in same way adopting requestanimationframe allowed schedule animations , maximize our chances of hitting 60fps, requestidlecallback schedule work when there free time @ end of frame, or when user inactive.

sadly, it's experimental feature , supported in chrome canary only.


Comments

Popular posts from this blog

Django REST Framework perform_create: You cannot call `.save()` after accessing `serializer.data` -

Why does Go error when trying to marshal this JSON? -