WebP 图像替换

发布于 2024-12-18 10:05:05 字数 1021 浏览 3 评论 0原文

我的最终目标是检测浏览器是否能够显示 webp 图像。如果是,请将页面上的所有图像替换为其 webp 等效项(位于同一目录中,名称相同,只是扩展名不同)

目前我有一个脚本,可以成功检测浏览器是否能够显示 webp 的

(function(){
  var WebP=new Image();
  WebP.onload=WebP.onerror=function(){
    if(WebP.height!=2){
      console.log("You do not have WebP support.");
    } else {
      console.log("You do have WebP support.");
    }
};
  WebP.src='data:image/webp;base64,UklGRjoAAABXRUJQVlA4IC4AAACyAgCdASoCAAIALmk0mk0iIiIiIgBoSygABc6WWgAA/veff/0PP8bA//LwYAAA';
        })();

情况下有 webp 支持我尝试了以下代码但没有成功。

// replace .gif with .webp
var allImages = document.body.getElementsByTagName("img");
var length = allImages.length;
var i;
for(i = 0; i < length; i++){
  allImages[i].src.replace("png", "testtest");
  console.log(allImages[i]);
}

当放置在标题中时,控制台会正确显示所有图像标签,但源并未从原来的 filename.png 更改。

关于什么是错误的做法有什么想法吗?

编辑:我发现了为什么它没有加载图像的问题,感谢wsanville。然而,查看 chrome 中的网络选项卡仍然显示我正在加载 png 图像,现在也加载了 webp 图像。我怎样才能阻止 png 图像首先加载?

My end goal is to detect if the browser is capable of displaying webp images. If it is, replace all the images on the page with their webp equivalent (located in the same directory with the same name, just different extension)

Currently I have a script that successfully detects if the browser is able to display webp

(function(){
  var WebP=new Image();
  WebP.onload=WebP.onerror=function(){
    if(WebP.height!=2){
      console.log("You do not have WebP support.");
    } else {
      console.log("You do have WebP support.");
    }
};
  WebP.src='data:image/webp;base64,UklGRjoAAABXRUJQVlA4IC4AAACyAgCdASoCAAIALmk0mk0iIiIiIgBoSygABc6WWgAA/veff/0PP8bA//LwYAAA';
        })();

Inside the case for having webp support I have tried the following code but been unsuccessful.

// replace .gif with .webp
var allImages = document.body.getElementsByTagName("img");
var length = allImages.length;
var i;
for(i = 0; i < length; i++){
  allImages[i].src.replace("png", "testtest");
  console.log(allImages[i]);
}

When placed in the header the console does correctly show all of the image tags, but the source has not been changed from the filename.png that it originally was.

Any ideas on what is being done incorrectly?

Edit: I found found out the problem with why it was not loading the images, thanks to wsanville. Looking at the network tab in chrome however still reveals that I am loading both the png and now the webp image as well. How can I prevent the png image from loading in the first place?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

烟火散人牵绊 2024-12-25 10:05:05

replace 函数返回一个字符串,但不会改变它。您只需将值赋回:

allImages[i].src = allImages[i].src.replace("old", "new")

编辑评论:
所有浏览器都会下载图像的 src 属性中的相应文件。作为您方法的替代方法,我建议将文件名存储在 img 标记的不同属性中。

您的图像标签可能如下所示:

<img alt="" data-png-source="/path/to/image.png" />

相应的 Javascript 可以将 src 属性设置为正确的版本。

var supportsWebP = true; //set this variable properly

for(i = 0; i < length; i++)
{
    var image = allImages[i];
    var pngSource = image.getAttribute('data-png-source');
    image.src = supportsWebP ? pngSource.replace('.png', '.webp') : pngSource;
}

The replace function returns a string, it doesn't mutate it. You just need to assign the value back:

allImages[i].src = allImages[i].src.replace("old", "new")

Edited for comment:
All browsers will download the corresponding file in the src attribute of an image. As an alternate to your approach, I suggest storing the file name in a different attribute of the img tag.

Your image tags could look like:

<img alt="" data-png-source="/path/to/image.png" />

The corresponding Javascript could set the src attribute to the correct version.

var supportsWebP = true; //set this variable properly

for(i = 0; i < length; i++)
{
    var image = allImages[i];
    var pngSource = image.getAttribute('data-png-source');
    image.src = supportsWebP ? pngSource.replace('.png', '.webp') : pngSource;
}
作业与我同在 2024-12-25 10:05:05

我知道这是一个非常古老的问题,但是当我寻找一种用相应的 jpg 替换 webp 图像的方法时,我没有找到太多。

通过 这篇文章,我将其放在一起,这似乎可以通过 IE 9 运行。

(它实际上可能可以使用旧的 jQuery 版本,但我使用的是 jQuery 2.1.1,它在 IE <= 8 中中断,所以我不确定)

它检查 .webp 支持,然后如果浏览器不支持 .webp,它将所有出现的文件替换为 .jpg 等效文件。

$(function() {
  var WebP=new Image();
  WebP.onload=WebP.onerror=function(){
    if(WebP.height!=2){
      $('img[src$=".webp"]').each(function(index,element) {
        element.src = element.src.replace('.webp','.jpg');
      });
    }
  };
  WebP.src='data:image/webp;base64,UklGRjoAAABXRUJQVlA4IC4AAACyAgCdASoCAAIALmk0mk0iIiIiIgBoSygABc6WWgAA/veff/0PP8bA//LwYAAA';
});

I know this a very old question, but as I looked for a way to replace webp images with corresponding jpgs, I didn't find much.

With this post, I put this together which seems to work through IE 9.

(It might actually work further back with an older jQuery version, but I'm using jQuery 2.1.1 which breaks in IE <= 8 so I'm not certain)

It checks for .webp support, then if the browser doesn't support .webp, it replaces all occurrences with a .jpg equivalent.

$(function() {
  var WebP=new Image();
  WebP.onload=WebP.onerror=function(){
    if(WebP.height!=2){
      $('img[src$=".webp"]').each(function(index,element) {
        element.src = element.src.replace('.webp','.jpg');
      });
    }
  };
  WebP.src='data:image/webp;base64,UklGRjoAAABXRUJQVlA4IC4AAACyAgCdASoCAAIALmk0mk0iIiIiIgBoSygABc6WWgAA/veff/0PP8bA//LwYAAA';
});
得不到的就毁灭 2024-12-25 10:05:05

如果您对服务器有(某些)控制权,则可以使用内容协商而不是 JavaScript。请参阅http://httpd.apache.org/docs/2.2/content-negotiation。 html 了解它在 Apache 中是如何完成的。

If you have (some) control of the server, you can use content negotiation instead of javascript. See http://httpd.apache.org/docs/2.2/content-negotiation.html for how it's done in Apache.

童话里做英雄 2024-12-25 10:05:05

您实际上正在尝试解决经典响应式图像问题的变体。

更改图像 src 属性时遇到的问题是,现代浏览器会向前看并开始下载带有错误扩展名的图像。您可能不想下载不会使用的图像。

诀窍是将图像放置在 noscript 标记内,然后通过在读取标记的 textContent 时更改路径来逐步增强图像。在旧版浏览器中,您将需要一个简单的polyfill来读出noscript标签的内容。

您可以查看我关于响应式图像和 webP 支持的系列 这里此处查看基于 Ethan Marcotte 经典响应式设计的示例。

You are actually trying to solve a variation of the classic responsive image problem.

The problem you have with changing the image src attributes is that a modern browser will look ahead and start downloading images with the wrong extension. You probably don't want to download images you aren't going to use.

The trick is to place the image inside a noscript tag, then progressively enhance that by changing the path as you read the textContent of the tag. In older browsers you will need a simple polyfill to read out the content of noscript tags.

You can view my series on responsive images and webP support here. View an example here based on Ethan Marcotte's classic responsive design.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文