简体   繁体   English

图像的高度和宽度自动吗?

[英]image height and width automatically?

Is it possible to make my img tags generate their width and height attributes automatically, for performance purposes? 是否可以使我的img标签出于性能目的自动生成其widthheight属性?

Usually, articles on web performance state that an image that includes its width and height attribute tags may load faster, relieving the browser from having to search for those values during the loading process. 通常,有关网络性能的文章指出,包含其widthheight属性标签的图像可能会更快加载,从而使浏览器不必在加载过程中搜索这些值。

The width and height attributes do not make the image load faster, and the browser is not "searching" for those values. width和height属性不会使图像加载更快,并且浏览器也不会“搜索”这些值。 What adding them does do is create a placeholder on the page that allows the browser to render other elements on the page in their proper places without having to reflow the page after the image finally loads. 添加它们的作用是在页面上创建一个占位符,该占位符使浏览器可以在页面的其他适当位置呈现其他元素,而不必在图像最终加载后重新排版页面。

To answer your question, there's no way to automatically generate these attributes, aside from some server-side solution that retrieves the image width and height from the file and writes the attributes to the page based on that. 要回答您的问题,除了某些服务器端解决方案之外,没有其他方法可以自动生成这些属性,该解决方案从文件中检索图像的宽度和高度,然后根据该属性将属性写入页面。 However, unless you're already doing other image processing (generating a thumbnail for instance), this is overkill and will likely waste more time on the server-side than you will save on the client-side. 但是,除非您已经在进行其他图像处理(例如生成缩略图),否则这是过大的,并且可能会比在客户端上浪费更多的时间在服务器端浪费时间。

Additionally, in certain scenarios, such as implementing responsive designs, it's actually preferable to not add the attributes, since you need to leave it up to the browser to determine how the page should flow and the image should display based on the resolution of the device. 此外,在某些情况下,例如实施响应式设计,实际上最好不要添加属性,因为您需要将其留给浏览器来确定页面应该如何流动以及图像应基于设备的分辨率显示。

I believe is not a question of a faster loading but probably of a faster rendering... 我相信这不是加载速度更快的问题,而是渲染速度更快的问题...

Anyway, you could use jQuery to generate those attributes but it won't probably change anything as jQuery takes time also to change those attributes and the images should be already loaded to get its dimensions. 无论如何,您可以使用jQuery生成那些属性,但是它可能不会改变任何东西,因为jQuery还需要时间来更改那些属性,并且图像应该已经加载以获得其尺寸。

From the API : API中

In cases where code relies on loaded assets (for example, if the dimensions of an image are required), the code should be placed in a handler for the load event instead. 如果代码依赖于已加载的资产(例如,如果需要图像的尺寸),则应将代码放置在用于加载事件的处理程序中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM