innerHTML 属性的使用非常流行,因为他提供了简单的方法完全替代一个 HTML 元素的内容。另外一个方法是使用 DOM Level 2 API(removeChild, createElement, appendChild)。但很显然,使用 innerHTML 修改 DOM tree 是非常容易且有效的方法。然而,你需要知道 innerHTML 有一些自身的问题:
当 HTML 字符串包含一个标记为 defer 的 script 标签(<script defer>…</script>)时,如 innerHTML 属性处理不当,在 Internet Explorer 上会引起脚本注入攻击。
设置 innerHTML 将会破坏现有的已注册了事件处理函数的 HTML 元素,会在某些浏览器上引起内存泄露的潜在危险。
还有几个其他次要的缺点,也值得一提的:
你不能得到刚刚创建的元素的引用,需要你手动添加代码才能取得那些引用(使用 DOM APIs)。
你不能在所有浏览器的所有 HTML 元素上设置 innerHTML 属... 3 条评论 »
2008-6-17 下午 - JS/Ajax/AS/Flex - innerHTML - 优化
优化网站性能的14条规则(更新)
1. 尽可能的减少 HTTP 的请求数
[content]
2. 使用 CDN(Content Delivery Network)
[server]
3. 添加 Expires 头(或者 Cache-control )
[server]
4. Gzip 组件
[server]
5. 将 CSS 样式放在页面的上方
[css]
6. 将脚本移动到底部(包括内联的)
[javascript]
7. 避免使用 CSS 中的 Expressions
[css]
8. 将 JavaScript 和 CSS 独立成外部文件
[javascript] [css]
9. 减少 DNS 查询
[content]
10. 压缩 JavaScript 和 CSS (包括内联的)
[javascript] [css]
11. 避免重定向
[server]
12. 移除重复的脚本
[javascript]
13. 配置实体标签(ETags)
[css]
14. 使 AJAX 缓存
[content]
详细请看:Best Practices for Speeding Up [...]
...
8 条评论 »
2008-3-22 下午 - 网站优化 - 优化
今天 承志 看到的,感觉比较有收获,分享一下:
When generating hyperlinks, always include a trailing slash if possible. For instance, navigating to http://msdn.microsoft.com/ie takes one more roundtrip than http://msdn.microsoft.com/ie/. When the browser navigates to the /ie url, the server merely sends down a 301 to the /ie/ url. Both links work, but the second version is faster.
也就是说,在地址栏中发送 URL:http://msdn.microsoft.com/ie ,服务器将会产生一个 301 转向至 [...]
...
7 条评论 »
2008-3-18 下午 - 网站优化 - URL - 优化
function replaceHtml(el, html) {
var oldEl = typeof el === “string” ? document.getElementById(el) : el;
/*@cc_on // 原始的 innerHTML 在 IE 中的性能好一点
oldEl.innerHTML = html;
return oldEl;
@*/
var newEl = oldEl.cloneNode(false);
newEl.innerHTML = html;
oldEl.parentNode.replaceChild(newEl, oldEl);
/* 一旦我们从 DOM 上移除老的元素,则返回新的元素引用。*/
return newEl;
};
此方法大大提高了 innerHTML 在 Firefox 和 Safari 上的性能。replaceHtml() 在 Firefox 2.0.0.6 里 destroy 与 replace 的速度各快了 473 倍以及 50 倍。而在 Safari 3.0.3 beta 上则是 [...]
...
5 条评论 »
2008-3-4 下午 - JS/Ajax/AS/Flex - DOM - innerHTML - 优化