1

So I have a small jQuery script that resizes elements according to their background image's aspect ratio. In certain instances, it doesn't work in time, and I believe this is because the code runs before the images finish downloading.

Basically, I have <div> elements that will have a certain sized background image, and I want the element to be the exact same size. If there is a better way than with JS, I'm all ears.

I can manually set a delay, but is there a way to ONLY run the code after the images finish downloading?

I currently have it in $(document).ready(function(){...}); inside my footer.

AKor
  • 8,550
  • 27
  • 82
  • 136
  • 3
    Maybe this might help? http://stackoverflow.com/questions/544993/official-way-to-ask-jquery-wait-for-all-images-to-load-before-executing-somethin – jhack Dec 02 '16 at 16:17
  • Another link which might be useful https://css-tricks.com/snippets/jquery/run-javascript-only-after-entire-page-has-loaded/. – Buddhi Madarasinghe Dec 02 '16 at 16:20

1 Answers1

7

Please try

    $(window).on("load", function() {
       // your logic here.
    });

Instead of

    $(document).ready(function(){...});

Note - load is called when all assets are done loading, including images. ready is fired when the DOM is ready for interaction.

Gurmeet Singh
  • 774
  • 8
  • 21