Deeply thought of javascript dynamic image resize
Dynamic image resizing is a useful functionality for forums and blogs, it widely spread and be used by many web-based systems.
Quchao.com posted a self-used images resizing encapsulation which I look deep into it and found massive improvable spaces.
http://www.quchao.com/entry/my-resizeimgs-func/#comment-3148
Quchao.com posted a self-used images resizing encapsulation which I look deep into it and found massive improvable spaces.
http://www.quchao.com/entry/my-resizeimgs-func/#comment-3148
function resizeImgs() {
if (!document.getElementsByTagName) {
return;
}
var defaultWidth = 400; // Defualt value for the images to be resized
var imgs = document.getElementsByTagName('img');
var imgsLen = imgs.length;
for (var i = 0; i < resize =" imgs[i].getAttribute('resize'))" width =" resize;" width =" defaultWidth;">
//Sorry, currently Chinese only. I will update this to English soon.
遍历的话使用
for 在"杀猫贴"中会导致IE假死,解决的办法是使用 setTimeout来做,
但是setTimeout最小值只能为10,速度太慢.
而对于image完全可以使用document.images来定位,而不必遍历所有的ELEMENT,速度会快很多.
如果使用
for (var i = 0 ; i < document.images[document.images.length]; i++){
document.images....
}
放在文档的最后去做的话,速度会快很多,而且不需要window.onload
图片也可以在第一时间设置为指定大小.
但该方法不能很好够unobtrusively的形式对功能进行封装,因为无法确定最后使用者也能够正确的将Script放在document的最后,而且不够灵活.
要解决这个问题,就必须使用到document.onreadystatechange
当页面LAYOUT完成而图片未加载是,就开始执行JS代码
document.onreadystatechange = function(){
if (document.readyState == "interactive"){
alert(document.images[document.images.length -1].readyState);
}
Labels: coding, javascript