是否可以更改图像 src="";在原始图像加载之前 [英] Is it possible to change out an image src="" before the original image loads

查看:47
本文介绍了是否可以更改图像 src="";在原始图像加载之前的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在研究可以更改图像 src 的 Javascript.我只是想知道这是否可以在浏览器尝试获取原始图像之前完成.

I've been looking at Javascript that can change the src of an image. I'm simply wondering if this can be done before the browser attempts to fetch the original image.

示例.

Src="Large-Image"

我可以(使用 javascript,我想可能是 node.JS 吗?)为用户服务 src="smaller-image" 吗?

Can I (with javascript, I would imagine.. node.JS maybe?) serve the user src="smaller-image"?

显然,如果浏览器先加载大图片,则不会有性能提升.

Obviously, there would be no performance gain if the browser loads the large image first.

推荐答案

我不这么认为,JS 需要 image-tag 来访问属性,所以它必须在此之后执行(就像在documentReady 或放置在标签之后),但此时浏览器已经开始下载图像.

I don't think so, JS needs the image-tag to be available to access the attributes, so it has to execute later than that (Like on a documentReady or by being placed after the tag), but at that point the browser has already started downloading the image.

但是,我见过一些解决方案,您不在src"属性上设置 url,而是在另一个属性名称上设置 url,例如data-src".您的 Javascript 可以将该 url 动态设置为src"属性以提示浏览器开始下载.

However, I have seen solutions where you don't set the url on the "src" attribute, but on another attribute name, like "data-src". Your Javascript can dynamically set that url to the "src" attribute to prompt the browser to start downloading.

例如(假设 jQuery 已加载):

For example (assuming jQuery is loaded):

<img data-src="http://www.url.nl/image.png" />

<script>
    $("img").each(function (index, element) {
       var $element = $(element);
       var imageUrl = $element.attr("data-src");

       //Do your checks here to change the image-url to a smaller one when required

       $element.attr("src", imageUrl);
    });        
</script>

这篇关于是否可以更改图像 src="";在原始图像加载之前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆