1

我无法解决这个问题。我在一个HTML页面中有几个 Div。每个 Div 代表一个不同的部分,因此包含该部分的不同图像。所有图像均从 css 引用并使用 javascript ( document.getElementById('DIV').style.display='none/block';) 显示/删除。

出于本示例的目的,假设我有 2 个 div。每个部分 Div(Div1 & Div2) 将是父 div,并且这些父级中的任何 Div 都将是其子级。(DIV1a,DIV2a)

我发现如果使用 display: block 设置 Div1 并使用 css Background-image:.... 而 Div2 是display='none'当我使用它隐藏 Div1 时style.display = 'none';它确实将其从屏幕上删除并允许我显示 Div2 ..但是background-image 仍然存在于浏览器内存中。

有趣的是,如果我将 background-img 放入 DIV1 中的子 div(div1a) 中,当我使用style.display = 'none'父 DIV1 时,子 div1a 图像确实会从浏览器内存中删除我style.display = 'none'在父 DIV1 上使用。但是我发现这也不一致....它似乎适用于某些父 div 而不适用于其他 div。

正如你可能知道的那样,我很困惑,真的不知道如何解决这个问题。

谢谢大家的时间和想法。

代码示例:

使用此方法时

<div id="Div1">
    content....
</div>

<div id="Div2" style="display: none">
    ...content
</div>

div#Div1{
    background-image: url(images/mybg.png);
    background-repeat: no-repeat;
    width: 480px;
    height: 360px;
}

document.getElementById("Div1").style.display='none';
document.getElementById("Div2").style.display='block';

当我执行上述 javascript 时,图像仍然存在于资源选项卡中

使用此方法时:

<div id="Div1">
    <div id="Div1a">
        content....
    </div>
</div>

<div id="Div2" style="display: none">
    content....
</div>

div#Div1a{
    background-image: url(images/mybg.png);
    background-repeat: no-repeat;
    width: 480px;
    height: 360px;
}

document.getElementById("Div1").style.display='none';
document.getElementById("Div2").style.display='block';

当我执行上面的 javascript 时,图像会从资源选项卡中删除......但这种效果不一致并且并不总是有效:s

4

1 回答 1

4

Setting something to display: none does not remove anything from memory in any browser. The entire DOM element is still in the DOM occupying the same amount of memory, it is just marked hidden from view and layout.

If you want to actually remove an element from memory, then you need to physically remove it from the DOM, usually using parent.removeChild(child) AND make sure that there are no references to the DOM element anywhere in your javascript which would keep it from getting garbage collected.


Also, I don't know how you are assessing memory usage in your browser, but most methods will not accurately detect whether a browser has freed a given image or not because the memory may have been freed from an internal pool of memory (available for reuse), but not returned to the OS. Just releasing an image will not necessarily show a reduction in memory usage by the browser. What does show would be highly browser specific and even OS specific and would certainly depend upon exactly what tools you were using to examine memory usage.

于 2012-09-06T17:04:26.430 回答