I have created a jquery animation with a CSS file containing some images (as background images).
To ensure that images are being loaded before starting the animation (also to prevent render blocking css file), I add the CSS file on the fly. I wait for CSS file to be loaded completely and also I use preloading technics for images but both fail. When I test the animation in slow network connection, The animation starts working and images are being loaded during the animation. This is my code logic:
- I wait for CSS to be loaded (first block of codes).
- I start preloading Images. (
loadImages()
) - I start the animation when all images are loaded (
startAnimation()
):
JS codes:
//Preloading CSS file before the animation starts:
var link = document.createElement('link');
link.setAttribute("rel", "stylesheet");
link.setAttribute("type", "text/css");
link.onload = function(){ loadImages(); } // also tried loadImages without ()
link.setAttribute("href", 'banner.css');
document.getElementsByTagName("head")[0].appendChild(link);
//PreLoading images I used in banner.css
var sumImage=0;
function loadImages(){
var imageFiles=[];
var images=["map1","map2","map3"];
for (var i=0; i<images.length; i++){
imageFiles[i] = new Image();
imageFiles[i].onload= sumImages(); // also tried sumImages without ()
imageFiles[i].src="banner/"+ images[i] +".png";
}
}
function sumImages(){
sumImage++ ;
//Starting animation when I ensure that all 3 images are loaded
if (sumImage== 3){startAnimation();}
}
I have also removed parentheses when calling sumImages()
and loadImages()
as my question was marked as duplicate of this question but nothing changed.