Am using Preload JS to load my images. Some of these images however need to be injected as background-images in CSS. However this doesn't work.
When I pass my 'background' to $('.main').css('background-image', 'url(' + img + ')'); the HTML is "background-image: url(http://127.0.0.1:8080/undefined);"
My issue is that I want to preload the image, get it via its ID and the write it to CSS Background Image. How do I do this?
Looking into the event the path is just - blob:http%3A//127.0.0.1%3A8080/3694c430-db8f-4543-a85e-9d1b9e8da50d
If I put the images into my CSS I can see it being double loaded. The CSS images being loaded and then PreloadJS loading them again.
I got it to work by travesing the Event of HandleFileLoad. Getting the ID and then injecting the event.result.currentSrc but it would need alot of code repetition.
if(event.item.id === 'slide1'){
$(".slide1").css({"background-image": 'url('+event.result.currentSrc+')'});
}
But this is hardly ideal if I have alot of images to push into backgrounds.
Any help would be appreciated.
Below is my code.
var preload;
var loader;
var manifest;
manifest = ([
{id: 'background', src:'Main_1_Background.jpg'}
]);
preload = new createjs.LoadQueue(true, 'img/');
preload.on('fileload', handleFileLoad);
preload.on('progress', handleOverallProgress);
preload.on('fileprogress', handleFileProgress);
preload.on('error', handleFileError);
preload.setMaxConnections(5);
preload.loadManifest(manifest);
// File complete handler
function handleFileLoad(event) {
console.log(event);
console.log(event.item.id);
var img = preload.getResult("background",true);
$('.main').css('background-image', 'url(' + img + ')');
}
// File progress handler
function handleFileProgress(event) {
}
// Overall progress handler
function handleOverallProgress(event) {
}
// An error happened on a file
function handleFileError(event) {
}
You can not pass an image instance to CSS. CSS uses a string, so you could use the item's original source instead:
var imgSource = preload.getItem("background").src;
$('.main').css('background-image', 'url(' + img + ')');
Note that if you load the image using XHR (the default in PreloadJS), it may not pull from the cache, and instead load again. If you see this issue, I recommend using tag loading instead:
preload = new createjs.LoadQueue(false, 'img/');
Cheers.