Javascript: loading image in memory & displaying in a new document - javascript

I have a requirement where I need to create a new document on the fly and display an image in it. The url of the image is passed as a variable into the function.
newWin('folder/image.jpg');
The codes of this function:
function newWin(url){
var strg = '<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"></head><body>';
strg += '<img src ="'+url+'"></body></html>';
var myWindow = window.open("", "MsgWindow", "width=600, height=400");
myWindow.document.writeln(strg);
}
There is more to the contents of the new document that what is displayed here.
The image doesn't load all the time or loads on 3rd or 4th attempt. How do I pre-load the image in the memory so that it appears instantly? I am not sure how to implement new image() in this situation. Kindly help!

You can either
Preload the image with an Image object and hope the browser will cache it
Preload the image data, convert it into base64, and put that data into the new window's html.
Method 2 is alot of code and really only necessary when the preloading has to work 100% of the time.
So here is method 1:
function preloadWin(url){
var img = new Image()
img.src = url
img.onload = function (){
newWin(url)
}
}
Call preloadWin('folder/image.jpg') and it should open up the window once the image is loaded.

Related

Image src not being written to popup window body?

I need to print images using JavaScript. I couldn't find a jQuery solution to this, so I tried the following:
var printWindow = window.open('', 'Print Image', 'height=400,width=400');
printWindow.document.write('<html><head><title>Print Image</title></head><body></body></html>');
var img = printWindow.document.createElement('image');
img.src = 'http://ecx.images-amazon.com/images/I/51j68MN%2B99L._SL500_SS100_.jpg';
img.onload = function() {
printWindow.print();
printWindow.close();
};
printWindow.document.body.appendChild(img);
printWindow.document.close();
Unfortunately, the popup HTML is this:
<html><head><title>Print Image</title></head><body><image></body></html>
So it appears that the src attribute isn't being set for the image.
I had previously put the image tag in the document.write() function, but I discovered the print window was blank for some images. My theory was that the print window was opening before some of the images finished downloading and thus showed (and printed) blank. So that's why I tried this method.
Why isn't this working, and how can it be fixed?
printWindow.document.createElement('img');
use correct tag name
look at http://jsbin.com/nurohutatasi/1/
Have you tried
var img = new Image();
instead of
var img = printWindow.document.createElement('image');
<image> isn't a correct image tag (<img> is it)
You are appending the image before it is loaded. And also, closing the printWindow before the image load and print (the last two lines). img is the correct tag name:
var img = printWindow.document.createElement('img');
img.src = 'http://ecx.images-amazon.com/images/I/51j68MN%2B99L._SL500_SS100_.jpg';
img.onload = function() {
printWindow.document.body.appendChild(img);
printWindow.print();
printWindow.close();
};
//printWindow.document.body.appendChild(img);
//printWindow.document.close();

Get new image to only appear when loaded if source changed

I've been having a problem caused by the previous image staying on the screen until the next is loaded.
My program uses a flowchart where various images are needed for certain questions. I've been using the following code to change the source from one to another.
HTML:
<img class= 'right' id= 'imageBox' style= 'width: 20%; height: auto;' src= www.1stimage.com/>
javascript:
document.getElementById("imageBox").src = 'www.2ndimagesite.com';
If the computer has a slow connection, the first image could stay on the screen for up to 10 seconds before the next one shows up. How do I get it to not display anything until it's finished?
Thanks.
Preload the image and update the src after it's loaded:
var img = new Image();
var newsrc = 'www.2ndimagesite.com';
img.onload = function () {
document.getElementById("imageBox").src = newsrc;
};
img.src = newsrc;
You can change aproach a bit to achieve what you want.
You can preload images and after that just select what image to show. You can read more about this here: http://perishablepress.com/3-ways-preload-images-css-javascript-ajax/
You can make start loading new image async and change current image to image like loading spinner or some image, which shows that something is loading at the moment (example: ) On onload handler you will rewrite this spinner to loaded image.
I wanted to write ~ same that #nedt wrote. Btw, I don't think that his code will help you. I think you will achieve same effect as you said in answer. Anyway, he was first and his answer was close, so I will just use his example.
document.getElementById("imageBox").src = "loading image link"; // load spinner
var img = new Image(); // load image asynchronously
var newsrc = 'www.2ndimagesite.com';
img.onload = function () { // onload handler
document.getElementById("imageBox").src = newsrc;
};
img.src = newsrc;
So, old image was loaded on page loaded. You did some action, for example pressed button. If you have low speed, loading spinner will be shown and after new image is loaded async, new image will be shown. If you have enought speed, new image will appear immediately.
Hope this will help you!
document.images[i].complete
will be true if picture[i] source is loaded.
you could preload all pictures an dont show it until the status change.

Replace img src but have loading graphic display while image is downloading

I have a page that swaps some fairly large images in and out. There are too many to preload when the page initially loads so that is not an option. So what I need to do is load them as they are requested by the user. Right now I'm using jQuery to replace the img's src. This works fine but the images I am loading can be around 500KB and it looks bad as they paint down the screen as they are downloading. What I'd like to do is pop a loading gif on the page when the image is in the process of loading then have the loading gif disappear once the image is loaded. I'm struggling to find a way to do that though. Here is the JS/jQuery code that I have that just replaces the src.
var product = "bowl";
var image = "dog.jpg"; //this is actually pulled from a data attribute, but its just hardcoded here for an example
$("#images img[data-product="+product+"]").attr("src", "/img/tablesetting/"+image);
I made a working jsfiddle showing this principle
http://jsfiddle.net/kasperfish/c72RT/4/
I recently needed to do the same thing. Basically I wrapped the image in a container div. within the container I've added a span element with my ajax loader gif embedded. this span has to be hidden initially but gets visible when an ajax request is made. The span gets removed when the image is fully loaded.
before ajax call
$('#your_image_container').find('span').show();
on success
$('#your_image').attr('src', 'your/image/url').load(function() {
$('#your_image_container').find('span').fadeOut();
});
I made a jsfiddle showing this principle
http://jsfiddle.net/kasperfish/c72RT/4/
Preload the image.
var product = "bowl";
var imageSrc = "dog.jpg";
var imgEl = $("#images img[data-product="+product+"]");
// show loading graphic only if it's needed
var timer = setTimeout(function(){
imgEl.attr("src", "/img/loading.gif");
},50);
// preload image
var img = new Image();
img.onload = function() {
clearTimeout(timer);
imgEl.attr("src",imageSrc);
}
img.src = imageSrc;
$img.attr("src", newImage);
if (!$img.get(0).complete) {
$img
.hide()
.after("<img src=throbber>")
.on("load", function () {
$(this).show().next().remove();
});
}

do content added to DOM count for the total page load time?

I mean if I append some contents like this:
<body>
//contents
<script>body.appendChild('<img src="new.png">');
// other contents
</body>
the browser will fire window.onload considering only the original html or it will take in consideration the load of the new image too? (new.png) ?
Besides that code/markup being incorrect, it will consider the new image. To append it to the DOM will be to download whatever the src attribute points to.
However, if this code was placed inside of a window.onload = function() { ... }, then it wouldn't be considered because its download would not occur until your window was loaded.
Here is the code that would actually work...
var img = new Image;
img.src = 'http://www.gravatar.com/avatar/3535689c965d66db3d2a936ced96192a?s=32&d=identicon&r=PG';
img.alt = 'Example';
document.body.appendChild(img);
jsFiddle.

Preloading image gracefully in Javascript (without any JS library)?

I have an image with set src attribute.
I would like to replace image, but connection with the server is slow and time that it takes to load a new image is not negligible.
Is there possibility to create internal Image object, set kind of "onLoadListener" on it, load an image and then set it to original image src attribute?
You can pre-load images in JavaScript like this...
myImage = new Image();
myImage.onload = function () { alert("Loaded"); };
myImage.src = "logo.gif";
You can put the logic to pop the image on the page instead of alert-ing.

Categories

Resources