-1

It is now important for google to add explicit width and height on image, Now I have to add this manually on all my client sites, is there any way to add these attr on all images with JS/Jquery ? And pass the google pagespeed test.

I have tried using this code, its adding the attr but this doesnt remove the flag.

$(document).ready(function(){
  $('img').each(function(idx, img) {
    $(this).attr({
      width: img.naturalWidth,
      height: img.naturalHeight
    })
  });
});
Danish Adeel
  • 728
  • 4
  • 11
  • 27
  • 2
    It won't remove the flag most likely because adding the attributes using JS is too late in the page lifecycle for them to be effective. You need to put them in the actual HTML source. – Rory McCrossan May 27 '21 at 07:56
  • 1
    If this has anything to do with google search, they index the pre-rendered page (no javascript), so a jquery solution wouldn't have an effect. – Kinglish May 27 '21 at 07:57
  • 1
    @Kinglish that isn’t really true any more, Google has crawling technology that can interpret JS. – CBroe May 27 '21 at 08:00
  • @Kinglish it's for [lighthouse] which is built-in to Chrome: F12/lighthouse tab then reload your page. It runs all sorts of analysis, one of which is whether `` tags have `height=` and `width=` attributes. Adding these *after* the analysis has run has no impact on the analysis. And as noted above would have no impact on *page render* time as the `img` tag would render with no size, load the image and force a page re-layout as it gets the image size. If the img tag has dimensions when first rendered, the page doesn't need to re-layout giving a potentially substantial speed increase. – freedomn-m May 27 '21 at 08:19
  • @CBroe It means there is no solution with JS ? – Danish Adeel May 27 '21 at 08:47
  • 3
    _Any_ attempt that relies on the image dimensions to be determined _by the client_ itself, is of course pointless. The whole purpose of this is to _tell_ the client about the image dimensions upfront. – CBroe May 27 '21 at 08:55
  • The only "JS" solution would be to write a script that updates all your html sources (be it .html/.cshtml/DB driven) - but javascript would unlikely be a good solution for that. – freedomn-m May 27 '21 at 09:09

2 Answers2

0

Just adding height and width attributes won't work you have to crop the images as well to its exact dimension. For example if you have set 100px height and width, the image height and width should also be 100px.

-1

Try using

$(window).load(function() {}

instead of

$(document).ready(function(){}
Jawwad Ahmed
  • 302
  • 1
  • 10
  • 1
    Not my downvote, but if `document.ready` isn't working then moving the logic to be executed *even later* with `window.load` isn't going to fix the problem. – Rory McCrossan May 27 '21 at 08:49