解决 IE6 内存泄露的另类方法

作者:blank 来源:怿飞blog 时间:2008-07-06 23:05:00 

Hedger Wang 在国内 blog 上得到的方法:使用 try … finally 结构来使对象最终为 null ,以阻止内存泄露。

其中举了个例子:


function createButton() {
    var obj = document.createElement("button");
    obj.innerHTML = "click me";
    obj.onclick = function() {
        //handle onclick
    }

    obj.onmouseover = function() {
        //handle onmouseover
    }
    return obj;//return a object which has memory leak problem in IE6
}

var dButton = document.getElementsById("d1").appendChild(createButton());
//skipped....

对于 IE6 中,引起内存泄露的原因,可看《Understanding and Solving Internet Explorer Leak Patterns》一文。

上面的例子,应该属于上文中的 “Closures”原因。

再看下用 try … finally 的解决方法:

/**
     * Use the try ... finally statement to resolve the memory leak issue
*/
 function createButton() {
    var obj = document.createElement("button");
    obj.innerHTML = "click me";
    obj.onclick = function() {
        //handle onclick
    }
    obj.onmouseover = function() {
        //handle onmouseover
    }

    //this helps to fix the memory leak issue
    try {
        return obj;
    } finally {
        obj = null;
    }
}

var dButton = document.getElementsById("d1").appendChild(createButton());
//skipped....

可能大家有疑问: finally 是如何解析的呢?

答案是:先执行 try 语句再执行 finally 语句。

例如:


function foo() {
    var x = 0;
    try {
        return print("call return " + (++x));
    } finally {
        print("call finally " + (++x));
    }
}

print('before');
print(foo());
print('after');

返回的结果为:
print » before
print » call return 1
print » call finally 2
print » true
print » after

更多详细的演示:《Finally, the alternative fix for IE6’s memory leak is available》

标签:内存,ie,方法,浏览器
0
投稿

猜你喜欢

  • 设计地址栏透明icon图标方法

    2008-10-25 16:42:00
  • Oracle学习笔记(五)

    2012-01-05 18:52:30
  • 能介绍一下NameSpace常用的地方吗?

    2009-11-01 18:11:00
  • 使用HTML和MSXML6.0 创建一个超轻量级XPATH测试程序

    2009-04-24 12:38:00
  • 关于document.cookie的使用

    2008-03-25 12:07:00
  • WEB2.0网页制作标准教程(12)XHTML校验及常见错误

    2008-02-19 19:59:00
  • 让XML在ASP中发挥其长处

    2008-01-16 19:07:00
  • SQL SERVER查询所有数据库名,表名,和字段名的语句

    2012-01-05 19:25:26
  • Dreamwaver 常见问答解答

    2009-07-05 18:51:00
  • 用画为5.12地震受灾同胞们祈福 Ⅱ

    2008-05-31 07:37:00
  • 个人网站与动网整合非官方方法

    2009-07-05 18:42:00
  • ASP同一站点下gb2312和utf-8页面传递参数乱码的终极解决方法

    2011-02-20 11:00:00
  • Oracle捕获问题SQL解决CPU过渡消耗

    2010-07-21 13:14:00
  • 实现一个获取元素样式的函数getStyle

    2009-02-10 10:37:00
  • asp实现ACCESS数据库加密方法

    2008-04-18 12:33:00
  • Oracle 子程序参数模式,IN,OUT,NOCOPY

    2009-10-23 18:08:00
  • 用ASP和SQL语句动态的创建Access表

    2008-10-14 16:59:00
  • 网站细节论(1)--阅读的细节

    2007-12-21 12:16:00
  • 分享很实用的css圆角写法[百度有啊提取]

    2009-01-06 13:05:00
  • 白话Block Formatting Context

    2010-08-03 12:36:00
  • asp之家 网络编程 m.aspxhome.com