I found myself needing to run a script to make minor adjustments to the page based on the size of an image, to keep things tidy. The problem I was having was using JQuery’s $(document).ready the script was executing as soon as the DOM was ready which is too early. The other option is to use $(window).load which runs only when the whole page has loaded, guaranteeing that I will get the image width and I can make my adjustments. The script below is used to make the image caption the same width as the image.

$(window).load(function () {
  imgWidth = $("#mainImg").attr("width");
  var caption = $(".imgCaption");
  if (imgWidth < 300) {
      captionWidth = imgWidth - (parseInt(caption.css("padding-left")) + parseInt(caption.css("padding-right")));
      caption.css("width", captionWidth+"px");
  }
});