document.execCommand()的作用

document.execCommand("BackgroundImageCache",false,true)解决ie6下的背景图片缓存问题

IE6下的背景图片每次使用都会重新发送请求(not 本地),连一个hover效果时候同样的背景图片仅仅位置不同而已,ie6都会再次发送请求,这个令人崩溃的事情需要解决掉:
对于ie来说,filter:expression 很强大,能够实现的功能超级多,但是更对于视效率如生命的程序员来说,它的效率不敢令人恭维,所以有人会用css方法实现ie6下背景图片缓存,但是这种人也就是崇拜微软的强大而已,无它,

html {filter:expression(document.execCommand("BackgroundImageCache", false, true));}

当然大多数人都会选择js方法实现:

(function(){
try{
var userAgent = navigator.userAgent.toLowerCase();
var env = null;
var ver = 0;
env = userAgent.match(/msie ([\d.]+)/);ver = env ? parseInt(env[1], 10) : 0;
if(ver == 6){
try{
document.execCommand("BackgroundImageCache", false, true);
}catch(e){}
}
}catch(e){}
})();

另: 今天在分析拍拍网 新窗口打开: www.paipai.com页面时注意到下面这段脚本:

1
2
3
4
5
6
7
<!--[if IE 6]>
<script type="text/javascript">
// <![CDATA[
  document.execCommand("BackgroundImageCache", false, true);
// ]]>
</script>
<![endif]-->
s

当看到这段脚本时觉得非常好奇,这对于IE6做了什么限制?通过搜索知道,IE6默认不缓存背景图片,CSS每次更改图片的位置时都会重新发起图片请求,这样对于视觉上有一定的闪烁,但是我过去的项目竟然感觉不到这样的问题,后来发现原来我一直用CSS Sprite解决这类加载问题的(貌似CSS Sprite也会造成这种情况,难道是本地测试看不出来?)。看来今天又学到了一招,搞前端的也真不容易,尤其是那个让人无语的Internet Explorer 6。

下面再贴出一种不推荐的办法,那就是CSS里写入expression,为什么不推荐,主要是因为效率问题,CSS expression都会带来效率上的问题,所以要避免使用。

1
2
3
html {
  filter:expression(document.execCommand("BackgroundImageCache",false,true));
}

最后我把拍拍网 新窗口打开: www.paipai.com上的那段代码结合网上的一些讲解改动如下:

1
2
3
4
5
6
7
8
9
<!--[if IE 6]>
<script type="text/javascript">
//<![CDATA[
try {
  document.execCommand("BackgroundImageCache", false, true);
} catch(e) {}
//]]>
</script>
<![endif]-->
 
 
 
 
 
<input type=button value=剪切 onclick=document.execCommand('Cut')>
<input type=button value=拷贝 onclick=document.execCommand('Copy')>
<input type=button value=粘贴 onclick=document.execCommand('Paste')>
<input type=button value=撤消 onclick=document.execCommand('Undo')>
<input type=button value=重做 onclick=document.execCommand('Redo') id=button2 name=button2>
<input>
<input type=button value=删除 onclick=document.execCommand('Delete')>
<input type=button value=黑体 onclick=document.execCommand('Bold')>
<input type=button value=斜体 onclick=document.execCommand('Italic')>
<input type=button value=下划线 onclick=document.execCommand('Underline')>
<input type=button value=停止 onclick=document.execCommand('stop')>
<input type=button value=保存 onclick=document.execCommand('SaveAs')>
<input type=button value=另存为 onclick=document.execCommand('Saveas',false,'c:\\test.htm')>
<input type=button value=字体 onclick=document.execCommand('FontName',false,fn)>
<input type=button value=字体大小 onclick=document.execCommand('FontSize',false,fs)>
<input type=button value=刷新 onclick=document.execCommand('refresh',false,0)>
原文地址:https://www.cnblogs.com/fx2008/p/2295440.html