Pre-loading images with Javascript | Not Working - javascript

I have a masonry grid where the images are black and white and when you hover over them, the color images appear. They are not composite images. They are all separate. (I'm just sorting out bugs for someone else's code)
On initial hover after a fresh page load, there is a delay (and grey overlay) when hovering over. After the initial, it's of course instantaneous when it switches to the color photo.
So what I'm trying to do is pre load the images with some javascript, but I'm having trouble doing this. Below is what I have for code. Also, this is in Wordpress. Not sure if that matters.
All of the images are background images too, not hardcoded into the html. It's all background css. Thanks for any help!
<script language="JavaScript">
$('document').ready(function preloader() {
// counter
var i = 0;
// create object
imageObj = new Image();
// set image list
images = new Array();
images[0]="images/treatment_locations.jpg"
images[1]="images/community_news_events.jpg"
images[2]="images/success_stories.jpg"
images[3]="images/self_assessment.jpg"
images[4]="images/our_associates.jpg"
images[5]="images/treatment_programs.jpg"
images[6]="images/patient_portal.jpg"
images[7]="images/FAQ.jpg"
images[8]="images/what_to_expect.jpg"
// start preloading
for(i=0; i<=8; i++)
{
imageObj.src=images[i];
}
});
</script>

If you overwrite the src in each iteration, you're not giving the browser a chance to fetch the image. You probably only preload the last image.
Try:
var imageObjs = [];
$('document').ready(function preloader() {
// counter
var i = 0;
// set image list
images = new Array();
images[0]="images/treatment_locations.jpg"
images[1]="images/community_news_events.jpg"
images[2]="images/success_stories.jpg"
images[3]="images/self_assessment.jpg"
images[4]="images/our_associates.jpg"
images[5]="images/treatment_programs.jpg"
images[6]="images/patient_portal.jpg"
images[7]="images/FAQ.jpg"
images[8]="images/what_to_expect.jpg"
// start preloading
for(i=0; i<=8; i++)
{
var imageObj = new Image();
imageObj.src=images[i];
imageObjs.push(imageObj);
}
});

That's another aproach, where it stores only the images that were successfully loaded.
var imgObjs = [];
$(document).ready(function preloader() {
// images list
var images = [
'treatment_locations.jpg',
'community_news_events.jpg',
'success_stories.jpg',
'self_assessment.jpg',
'our_associates.jpg',
'treatment_programs.jpg',
'patient_portal.jpg',
'FAQ.jpg',
'what_to_expect.jpg'
];
for (var i in images) {
var img = new Image();
img.src = 'images/' + images[i];
// stores it on array after loading
img.onload = function() {
imgObjs.push(this);
};
}
});

Related

Image source not changing with JavaScript

Please answer this question, as I am struggling a lot with it.
I am trying to change image source on mouse over. I am able to do it, but image is not displaying on page.
I am trying to change image source to cross domain URL. I can see that in DOM image source is changing but on page its not.
I have tried all solutions mentioned in LINK, but none of them is working.
Please let me solution to problem.
NOTE:
I can see in network tab image is taking some time to download (about 1 sec).
It is an intermediate issue, sometime image is loading and sometimes its not
CODE:
document.getElementsByTagName('img')[0].addEventListener('mouseover', function()
{
document.getElementsByTagName('img')[0].setAttribute('src', 'url/of/the/image');
});
have you tried loading images before everything else?
function initImages(){
var imC = 0;
var imN = 0;
for ( var i in Images ) imN++;
for(var i in Images){
var t=Images[i];
Images[i]=new Image();
Images[i].src=t;
Images[i].onload = function (){
imC++;
if(imC == imN){
console.log("Load Completed");
preloaded = 1;
}
}
}
}
and
var Images = {
one image: "path/to/1.png",
....
}
then
if( preloaded == 1 ){
start_your_page();
}
Here the code that will remove the img tag and replace it with a new one:
document.getElementsByTagName('img')[0].addEventListener('mouseover', function() {
var parent = document.getElementsByTagName('img')[0].parentElement;
parent.removeChild(document.getElementsByTagName('img')[0]);
var new_img = document.createElement("img");
new_img.src = "https://upload.wikimedia.org/wikipedia/commons/6/69/600x400_kastra.jpg";
parent.appendChild(new_img);
});
<img src="https://www.w3schools.com/w3images/fjords.jpg">
I resolved the issue using code:
function displayImage() {
let image = new image();
image.src="source/of/image/returned/from/service";
image.addEventListener('load', function () {
document.getElementsByTagName('img')[0].src = image.src;
},false);
}
Here in code, I am attaching load event to image, source of image will be changed after image is loaded.

Why JavaScript code execute second part sometimes

I am draw background on canvas and also small images on that background. But sometimes, background draw on small images. Why ?
JavaScript code -
var canvasupdate = document.getElementById("myCanvas");
ctxupdate = canvasupdate.getContext("2d");
var background = new Image();
background.src = sitePath + "ATOM/chapter1/book/" + `bgimagename`;
background.onload = function() {
ctxupdate.drawImage(background, 0, 0); // set background image
};
var imageobj = new Array();
for (var d = 0; d < calloutImageArray.length; d++) // getting small images in array
{
imageobj[d] = new Image();
(function(d) {
imageobj[d].src = sitePath + "ATOM/chapter1/book/" + calloutImageArray[d];
imageobj[d].onload = function() {
ctxupdate.drawImage(imageobj[d], calloutImageArrayX[d], calloutImageArrayY[d], calloutImageArrayW[d], calloutImageArrayH[d]);
};
})(d);
}
In above code, background image code should be execute first then call out image(small image) code execute but some time execute small images code and then background image code why?
All the images are loaded asynchronously. So sometimes the small images are loaded (and drawn) before the background image. Please take a look into e.g. Network tab in Chrome in which order the resources load is done.
The simplest solution for this problem is to move the loading of small images into the callback function for load event of the background image.
The onLoad function runs asynchronously. That means JavaScript will continue to run the rest of your code and will run the callback function when the background image is loaded. That's why your second part of the code runs first. So instead try to add your code inside the onload function like this:
var canvasupdate = document.getElementById("myCanvas");
ctxupdate = canvasupdate.getContext("2d");
var background = new Image();
background.src = sitePath + "ATOM/chapter1/book/" + `bgimagename`;
background.onload = function() {
ctxupdate.drawImage(background, 0, 0); // set background image
var imageobj = new Array();
for (var d = 0; d < calloutImageArray.length; d++) // getting small images in array
{
imageobj[d] = new Image();
(function(d) {
imageobj[d].src = sitePath + "ATOM/chapter1/book/" + calloutImageArray[d];
imageobj[d].onload = function() {
ctxupdate.drawImage(imageobj[d], calloutImageArrayX[d], calloutImageArrayY[d], calloutImageArrayW[d], calloutImageArrayH[d]);
};
})(d);
}
};
that way you can be sure that the background will be set first and then your small images. Note that I didn't try your code to check if it does what you want, I just rearranged the code blocks to show you the logic and why does not run as you would expect.
Hope it helps

Are there any alternatives for using toDataURL in Chrome?

The main problem is that I have to work with many images. And I can't use crossOrigin Attribute for all of them.
My code looks like this:
<script>
var c=document.getElementById('example');
var ctx=c.getContext('2d');
var LeftHand = new Image();
LeftHand.id="imq1";
var RightHand = new Image();
RightHand.id="imq2";
var Body = new Image();
Body.id="imq6";
boyBody.src = "https://getout-s3.s3.amazonaws.com/baseBody/boy-02.png";
LeftHand.src = "https://getout-s3.s3.amazonaws.com/NK4XtQvkZ4MGctZf_.hand(unisex)_13.png ";
RightHand.src = "https://getout-s3.s3.amazonaws.com/OPdFPcU2sORgNmTy_.hand(unisex)_9.png ";
Body.src = "https://getout-s3.s3.amazonaws.com/HRZqrTYSdJXGedgX_.Body_(m)7.png ";
boyBody.onload = function() {
ctx.drawImage(boyBody, 0, 0, boyBody.width/2, boyBody.height/2);
ctx.drawImage(LeftHand, (899 - LeftHand.width/2)/2, (867 - LeftHand.height/2)/2, LeftHand.width/2, LeftHand.height/2);
ctx.drawImage(Underwear, (599 - Underwear.width/2)/2, (845 - Underwear.height/2)/2, Underwear.width/2, Underwear.height/2);
ctx.drawImage(Body, (599 - Body.width/2)/2, (557 - Body.height/2)/2, Body.width/2, Body.height/2);
var img = c.toDataURL("image/png");
document.write('<img src="' + img + '" />');
};
</script>
Browsers don't let programmers export cross-domain content for very good security reasons. Your private banking info is cross-domain content that you don't want give to thieves using the canvas as an export device.
Therefore, context.toDataURL is disabled immediately after you drawImage a cross-domain image onto canvas. The same disabling is true for context.getImageData. (context.getImageData is another way to export canvas content).
To allow exporting the canvas content to your users, you will have to host all the images on the same domain as your webpage.
BTW, you must give all your elements time to load before drawing them. Here's an image loader that loads all your images in advance and then calls start() when all the images are fully loaded. Put your ctx.drawImage's in start().
// put the paths to your images in imageURLs[]
var imageURLs=[];
imageURLs.push("https://getout-s3.s3.amazonaws.com/baseBody/boy-02.png");
imageURLs.push("https://getout-s3.s3.amazonaws.com/NK4XtQvkZ4MGctZf_.hand(unisex)_13.png");
// ...etc, for all images
// the loaded images will be placed in imgs[]
var imgs=[];
var imagesOK=0;
loadAllImages(start);
function loadAllImages(callback){
for (var i=0; i<imageURLs.length; i++) {
var img = new Image();
imgs.push(img);
img.onload = function(){
imagesOK++;
if (imagesOK>=imageURLs.length ) {
callback();
}
};
img.onerror=function(){alert("image load failed");}
img.crossOrigin="anonymous";
img.src = imageURLs[i];
}
}
function start(){
// the imgs[] array now holds fully loaded images
// the imgs[] are in the same order as imageURLs[]
}

How to get JavaScript to rotate through a series if images

I'm having an issues where I cannot get my code to rotate multiple images in a cycle for my image gallery (just a bunch of images i got on google). I can however to get 1 image to cycle through the images but everything iv tried to get it to work with more than one has failed. Any help/ tips would be useful. Im in college for web development and i understand the basics of javascript it just seems when it comes to creating applications i have a bit of trouble.
Here is a link to my code: jsFiddle
$(document).ready(function () {
var img = document.images;
// Holds the image collection
var counter = 0;
var imgArray = [];
imgArray[0] = "http://www.zeroprox.tk/temp/images/img1.png";
imgArray[1] = "http://www.zeroprox.tk/temp/images/img2.jpg";
imgArray[2] = "http://www.zeroprox.tk/temp/images/img3.png";
imgArray[3] = "http://www.zeroprox.tk/temp/images/img4.jpg";
imgArray[4] = "http://www.zeroprox.tk/temp/images/img5.jpg";
imgArray[5] = "http://www.zeroprox.tk/temp/images/img6.png";
imgArray[6] = "http://www.zeroprox.tk/temp/images/img7.jpg";
imgArray[7] = "http://www.zeroprox.tk/temp/images/img8.png";
$("#left-arrow").click(function () {
if (counter < 0) {
counter = imgArray[counter] - 1;
} else {
counter--;
}
img[1].src = imgArray[counter];
});
// Left arrow... Previous
$("#right-arrow").click(function () {
counter = (counter + 1) % imgArray.length;
img[1].src = imgArray[counter];
});
// right arrow... Next
});
JSFiddle
Check this, it should solve your problem ;)
You were replacing every time the same image, now creates a new one and remove another.
Also added div#imagelist to use as a image container and access easier from JavaScript
var newImg = $(document.createElement("img"));
newImg.attr("src",imgArray[counter]);
$("#imagelist img").last().remove();
$("#imagelist").prepend(newImg);

Javascript image preloader doesn't show status

I put together an image preloader which works fine, but what doesn't work is updating the status after every image that has been loaded. Instead, all images are loaded and "done" (last line) is the only thing that shows up. It does work when I use an alert instead of the innerHTML command, but that is obviously of no use. What am I doing wrong?
<div id="preloader">
<span id="preloader_status"> </span>
<script language="JavaScript">
imageObj = new Image();
images = new Array();
images[0]="bigimage.gif"
images[1]="anotherbigimage.gif"
/* and so on */
var i = 0;
var o = (images.length);
for (i=0;i<o;i++) {
var status = (Math.round(100*(i/o)));
imageObj.src=images[i];
document.getElementById("preloader_status").innerHTML = status;
}
document.getElementById("preloader_status").innerHTML = "done";
</script>
</div>
To show image load progress, you will need to hook into the onload event for the images so you can track when their loading is actually complete. Images are loaded asychronously so assigning .src only STARTS the loading of the image. It is not completed until later when the onload handler is called. Because of that, your existing code will just immediately show "done" because it isn't tracking when the images are actually done loading.
In addition, you were successively assigning a new .src value to the same image object which is going to abort the previous image loading. You need to create a new image object for each new image you are loading.
You can fix your code like this:
<div id="preloader">
<span id="preloader_status"> </span>
<script language="JavaScript">
var imageSrcs = [
"bigimage.gif",
"anotherbigimage.gif"
/* and so on */
];
function preloadImages(list, statusID) {
var img, cnt = 0;
var progress = document.getElementById(statusID);
var preloads = [];
for (var i = 0; i < list.length; i++) {
img = new Image();
img.onload = function() {
++cnt;
var loadPercent = Math.round(100*(cnt/list.length));
progress.innerHTML = loadPercent;
if (cnt == list.length) {
progress.innerHTML = "done";
}
}
img.src = list[i];
preloads.push(img);
}
}
preloadImages(imageSrcs, "preloader_status");
</script>
</div>
The for loop will happen almost instantly, because images load asynchronously; setting imageObj.src will just start the image request and move on to the next. It will not block the execution of the loop. This will cause the effect you're seeing, i.e the last line of the code is executed straight away.
I think what you're looking for is the JavaScript Image onload event, which will fire when an image has finished loading.
var image = new Image();
image.onload = function() {
// always called
alert('image loaded');
};
image.src = 'image.jpg';
Code was pinched from this article.

Categories

Resources