Modal performance in browsers, or, exploiting z-index
I did a little test. I am using jQuery UI’s dialog, and setting it to be draggable. Pretty standard stuff — after all, dragging windows around your computer is commonplace.
A quick look into task manager and I see that dragging that modal around spikes the CPU to around 50%! (And this is with Chrome, an exceptionally fast browser.) Doing the same with a simple Windows file window pushes the CPU to only 10%. Further, the modal is always a few pixels behind the mouse, which feels sloppy to an end user.
Why does the browser need to work so hard to do the “same” thing? Well, the browser has no idea what a modal is. It simply knows that there is a chunk of HTML that is changing position. And so, with each microscopic change, the browser must recalculate the entire page’s layout, probably dozens of times per second. As with other jQuery tricks, we are hammering the DOM.
The goal of Google and other browser makers is to push performance so that Web apps feel like native apps. Of course, we need to keep browsers capable of working with standard HTML/JS/CSS — ignorant of the goals of that code — but certainly there are optimizations to be found.
Here’s one: a browser should infer when an HTML element is on a z-index that does not affect other parts of the DOM. It should then know to minimize the reflow redraw when that element moves. This would require many fewer layout calculations and CPU cycles.
Of course, this inference is easier said than done. It would need to look at all the z-indexes of all elements on the page, CSS position attributes, possibly some widths. (The browser maker might document that list of requirements, so that libraries could be optimized against them.) But once the browser makes this determination, the modal should perform at close to native speed.
Maybe it can’t be done. Maybe there is no correct determination of “independence” for one piece of the DOM.
But it would be interesting to find out. Dialogs and windows are such a fundamental part of UI’s and user experience that this would be a modest, yet substantial, step forward for the Web.