是否可以在图像开始加载之前运行javascript? [英] Is it possible to run javascript before images begin loading?
问题描述
我想在浏览器请求图像之前更改图像的src属性,目的是使用类似Timthumb的PHP脚本减小图像的大小.使用jQuery,我认为$(document).ready
可以解决问题:
I'd like to change the src attribute of images before they are requested by the browser, the aim being to reduce the size of the images using a PHP script like Timthumb. Using jQuery, I thought $(document).ready
would do the trick:
$(document).ready(function () {
var imgs = $('#container img');
jQuery.each(imgs, function() {
$(this).replaceWith('<img src="timthumb/timthumb.php?src=' + $(this).attr('src') + '&w=200" />');
});
});
但是未调整大小的原始图像仍会在后台下载到浏览器的缓存中.是否可以在客户端执行我想做的事情,还是服务器端是唯一的选择?
But the original, unresized image is still downloaded in the background to the browser's cache. Is it possible to do what I'm trying to do on the client side, or is server-side the only option?
推荐答案
浏览器将Javascript的加载和执行序列化(除非您使用类似head.js
之类的东西),但是问题在于DOM必须可用于脚本对其进行修改.可用的DOM在之后后触发jQuery ready事件,因此浏览器已经开始请求HTML中引用的资源.
Javascript loading and execution is serialized by the browser (unless you use something like head.js
), but the problem is that the DOM has to be available for a script to modify it. The jQuery ready event fires after the DOM is available, so the browser has already started requesting the resources that were referenced in the HTML.
因此,如果将Javascript放在图片标签之前,它将无法找到图片标签,并且一旦触发准备就绪,下载就已经开始.我不知道在加载图像之前会触发任何事件(对于中止只是一个事件),因此最干净的方法是首先使用修改后的src
属性创建HTML.
So if you put the Javascript before the image tag it won't be able to find the image tags, and once ready fires the download has already started. I'm not aware of any events that fire before image load (just one for aborts), so the cleanest method is to create the HTML with the modified src
attributes in the first place.
或者,将src
放在图像上的其他属性中(例如data_orig_src
),并在脚本准备就绪后运行脚本以将每个图像上的src
设置为data_orig_src
.更改src
之前,请使用CSS隐藏图像,以便用户看不到损坏的图像图标.我认为这可能比事后添加图像更好,因为您无需跟踪图像在DOM中的放置位置,并且效果也应更好.
Alternatively, put the src
in a different attribute on the image (like data_orig_src
) and run the script to set src
to data_orig_src
on each image upon document ready. Use CSS to hide the images before changing the src
so the user doesn't see a broken image icon. I think this is probably better than adding the images after the fact because you won't need to track where the images need to be placed in the DOM, and it should perform better as well.
当然,如果您可以将服务器更改为使用data_orig_src
而不是src
,那么为什么不首先将正确的src
放在标签中呢?
Of course if you can change the server to use data_orig_src
instead of src
, why not just put the proper src
in the tag in the first place...
这篇关于是否可以在图像开始加载之前运行javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!