更好的Applet体验:海报帧2011-08-31在本系列文章的第一部分中,我向你展示了如何使用设置加载时图片,包括动态的GIF自旋体图片。这次,我将向展示如何使用屏幕截图或海报帧去加快页面的加载。Quicktime电影就有海报帧的思想。电影中的一帧(经常就是其中的第一帧)将会放到该电影出现的地方。当用户点击海报帧时,实现的电影才会通过网络被加载进来。这就能极大地加快该电影所在Web页面的加载速度。使用少许JavaScript,完全可以为Java Applet实现相同的功能。Applet的海报帧在研究这个Demo之前,我必须要提到,我个人尚未在IE浏览器中测试过这个Demo。如果你发现这个Demo不能在某个浏览器中运行,请向错误信息发送给我,以便我能更新这个JavaScript。基本思想非常的简单,创建一个div,它包含一个链接和一张屏幕截图。当用户点击该链接时,我们使用一个新的applet元素去替换页面中的a和img元素。一旦浏览器察觉到了这个新的applet元素,它将下载Java插件并启动这个Applet。这就有一个例子:如果你点击了这张图片,一个Applet就会被加载到该图片所在的位置,并会说"applet loaded"。JavaScript如下就是这个JavaScript脚本:
<script>
function generateInlineAppletTag(appletID, screenshotID) {
var attributes = {
code:"animatedstartup.MainApplet",
width:100,
height:100,
archive:"http://projects.joshy.org/demos/AnimatedStartup/AnimatedStartup.jar",
id:"fooApplet"
};
var parameters = {
image:"http://projects.joshy.org/demos/AnimatedStartup.gif",
centerImage:"true"
};
var appletTag = document.createElement("applet");
for (var attribute in attributes) {
appletTag.setAttribute(attribute,attributes[attribute]);
}
if (parameters != "#ff0000" && parameters != null) {
for (var parameter in parameters) {
var param = document.createElement("PARAM");
param.setAttribute("name",parameter);
param.setAttribute("value",parameters[parameter]);
appletTag.appendChild(param);
}
}
var bodyRef = document.getElementById(appletID);
var screenshot = document.getElementById(screenshotID);
bodyRef.removeChild(screenshot);
bodyRef.appendChild(appletTag);
}
</script>