使用javascript settimeout加载图像时内存泄漏

时间:2013-06-06 07:06:42

标签: javascript html

我已经建立了一种监控系统,摄像机每秒拍摄一张照片,并将此图像发送到服务器,覆盖前一张照片。在客户端,我有一个简单的javascript settimeout每秒加载此图片

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

但这会导致内存泄漏,最终页面崩溃。 怎么可能避免这个?在这里缓存问题?浏览器是否每秒都会缓存每个新图像,这就是内存泄漏的原因?

1 个答案:

答案 0 :(得分:4)

可能是一个缓存问题,因为浏览器可能会缓存所有这些图像,因为它们每次都有新的图像名称(尽管这不应该是崩溃)。

在这种情况下,请在标题中设置这些缓存指令,看看它是否解决了问题:

<!-- 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" />

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

第三种可能的解决方案可能是使用普通的javascript来操作图像,以消除jQuery内存泄漏的可能性。

// 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();