简体   繁体   中英

Drawing a SVG with d3.js while tab is in background

Context : I am working on a webapp that has to display some fairly complicated and constantly updating (multiple times per second) SVG images. The updates stem from a seperate server and the SVG is updates as soon as an update is received by the web frontend. The webapp is written in Scala.js and the image is created using the d3js library (see also: scala-js-d3 ). We currently only support Google Chrome.

Problem : Once the webapp has been in a background tab for a while, the whole site gets unresponsive once navigated to again. Depending on how long the app was in the background, it sometimes takes up to 20 seconds for the application to be responsive again. Is there any way I can solve this?

The solution that works best for me is a pretty simple one:

Once the application is in a background tab or minimized (can be detected using the Page Visibility API ), I only update my model without drawing anything. Then, once the application is put into the foreground again, I re-draw everything. This fixed all of my performance problems.

I came across the same problem which I worked around by not doing transitions in background tabs.

mbostock shows a nice snippet for doing this at https://github.com/d3/d3-transition/issues/93#issuecomment-516452828

Helper method…

d3.selection.prototype.maybeTransition = function(duration) {
  return duration > 0 ? this.transition().duration(duration) : this;
};

…to be used the following way:

selection
  .maybeTransition(document.visibilityState === "visible" ? my_duration : 0)
    .attr(…

Capturing the page visibility events one could then even adapt the transition time in such a manner that the transition time is reduced (thus the transition sped up) in such a way that it ends in about the same time had the page not been in a background tab.

If you are using setInterval() at the moment the browser might be 'punishing' you for running setInterval() in an inactive browser-tab.

You can fix this by either using requestAnimationFrame() or by monitoring the tab visibility and only using setInterval() when the tab is active.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM