I do a preview of an element that has a repeating background. Depending on the large or small picture, the background should change through the background-size. I noticed that this only works in those cases if the picture has already been loaded into the cache (for example, from the second time if you go to the page). How to make the preview work correctly even if we open the page for the first time?

// вставляем изображение в src img $('.elements[action=1] img').attr('src', file); // получаем размер изображения var img_width = $('.elements[action=1] img').prop('naturalWidth'); // рассчитываем ratio для background-size var img_width_mini = img_width * 0.5; var img_width_big = img_width * 2; // вставляем в бекраунд в див $('.fon_mini').css('background-size', img_width_mini); $('.fon_big').css('background-size', img_width_big); 

    1 answer 1

    The script works out before the picture is loaded. Install a load event handler

     $('.elements[action=1] img').attr('src', file); $('.elements[action=1] img').load(function() { var img_width = $(this).prop('naturalWidth'); ... });