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

流过昼夜 提交于 2021-02-07 10:27:00

问题


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?


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/53042400/drawing-a-svg-with-d3-js-while-tab-is-in-background

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!