patternjavascriptMinor
Assigning width and height to specify image dimension using jQuery
Viewed 0 times
imageheightdimensionwidthjqueryusingandspecifyassigning
Problem
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:
Output: This method does fix the "Specify Image Dimensions" but it also removed some of my images on the website.
The second solution is:
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.
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.
Solution
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.
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.
Context
StackExchange Code Review Q#40489, answer score: 8
Revisions (0)
No revisions yet.