12
\$\begingroup\$

After testing my site against GTMetrix, I get warnings on not specifying image dimensions. I am working on a WordPress site. Here is my solution:

My first solution was:

    // Specify image dimensions
    $('img').each(function() {
        var findImgWidth = $(this).width();
        var findImgHeight = $(this).height();

        $(this).attr('width', findImgWidth);
        $(this).attr('height', findImgHeight);
    });

Output: This method does fix the "Specify Image Dimensions" but it also removed some of my images on the website.

The second solution is:

// Make sure img have been loaded
$().ready(function() {
    imageSize();
});
// Assign width/height to img
function imageSize() {
    // Specify image dimensions
    $('img').each(function() {
        var findImgWidth = $(this).width();
        var findImgHeight = $(this).height();

        $(this).attr('width', findImgWidth);
        $(this).attr('height', findImgHeight);
    });
}

Output: This solution seems to work. My images does not disappear, but I would like someone to help me go over the code to see if it's an efficient way to write.

\$\endgroup\$
2
  • 5
    \$\begingroup\$ Greetings, the reason GTMetrix complains is that the browser can render the page faster if it knows the size of the image. Setting the size after the browser has rendered is not going to make your page faster, it will only make the warning go away and fractionally make your page load slower. If you research this and agree, please close this question. \$\endgroup\$
    – konijn
    Jan 30, 2014 at 23:53
  • 4
    \$\begingroup\$ @konijn I think you're wrong ;-). This is a good question... and should not be closed. In fact, your comment would make a worthy answer, and you should convert it to one. \$\endgroup\$
    – rolfl
    Jan 31, 2014 at 0:50

1 Answer 1

8
\$\begingroup\$

The reason GTMetrix complains is that the browser can render the page faster if it knows the size of the image.

Setting the size after the browser has rendered is not going to make your page faster, it will only make the warning go away and fractionally make your page load slower.

This means you will have to declare the height and width of the image on the server side, or ignore the warning of GTMetrix.

\$\endgroup\$
1
  • \$\begingroup\$ Basically, there's no point in setting the image dimensions using jQuery if it wasn't specified before the browser renders then. Correct? \$\endgroup\$
    – rolu
    Jan 31, 2014 at 14:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.