使用javascript的settimeout加载图像时发生内存泄漏 [英] Memory leak when loading images with javascript's settimeout

查看:113
本文介绍了使用javascript的settimeout加载图像时发生内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经建立了一种监视系统,相机每秒都会拍摄一张照片,并将该图像发送到服务器,以覆盖前一个。在客户端,我有一个简单的JavaScript与 settimeout 来每秒载入此图片

  $(img)。attr(src,http://mysite/image.jpg?randomString =+ new Date()。getTime()); 

但是这会导致内存泄漏并最终导致页面崩溃。
如何避免这种情况?在这里缓存问题?浏览器缓存每一个新的图像,每一秒,这就是内存泄漏的原因吗?

/ em>是一个缓存问题,因为浏览器可能会缓存所有这些图像,因为它们每次都有新的图像名称(这不应该是一个崩溃)。在这种情况下,请在标题中设置这些缓存指令并查看它是否可以解决问题:

 <! -  disable在代理服务器上缓存 - > 
< meta http-equiv =pragmacontent =no-cache>
<! - 将到期日期设置为立即 - >
< meta http-equiv =expirescontent =0>
<! - 指示浏览器不缓存网页 - >
< meta http-equiv =cache-controlcontent =no-cache/>

另一方面,另一个问题可能是您的javascript。如果服务器无法及时处理http请求,则会在浏览器中排队很多未解析的http请求。尝试在这种情况下设置超时时间为5秒(= 5000毫秒)。



第三种可能的解决方案可能是使用纯javascript处理图像,以消除

  //缓存元素一次
var img = document.querySelector(img);

//在setTimeout中使用(不要在每次调用时创建一个新的时间对象):
img.src =/image.jpg?randomString =+ Date.now() ;


I have set up a kind of surveillance system, where camera is taking a photo every second and sending this image to server where it overwrites the previous one. On a client side I have a simple javascript with settimeout to load this image every second

$("img").attr("src", "http://mysite/image.jpg?randomString="+new Date().getTime());

But this causes memory leak and eventually the page crashes. How to possibly avoid this? Is caching the problem here? Does the browser caches every new image, every second and that's the reason for the memory leaks?

解决方案

It could be a caching problem because the browser might cache all these images since they have new image names each time (this shouldn't case a crash though).

In this case, set these caching directives in the header and have a look if it fixes the problem:

<!-- disable caching on proxy servers -->
<meta http-equiv="pragma" content="no-cache">
<!-- set expiration date to "immediately" -->
<meta http-equiv="expires" content="0">
<!-- instruct the browser to not cache the webpage -->
<meta http-equiv="cache-control" content="no-cache" />

On the other hand what might be another problem is your javascript. If the server is not able to handle the http requests in time, you queue up a lot of unresolved http requests in the browser. Try setting the timeout to say 5 seconds (= 5000 ms) in this case.

A third possible solution might be to manipulate the image with plain javascript to eliminate the possibility of jQuery memory leaks.

// cache the element once
var img = document.querySelector("img");

// use in setTimeout (Don't create a new Time Object on every call):
img.src = "/image.jpg?randomString="+Date.now();

这篇关于使用javascript的settimeout加载图像时发生内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆