I have a list of objects MyObject and that looks like this:
var Obj1 = {'ImgTop':'500px','ImgLeft':'200px','ImgSrc':'/image1.jpg'}
var Obj2 = {'ImgTop':'300px','ImgLeft':'100px','ImgSrc':'/image2.jpg'}
I load these objects into an array like this:
var AnimCycle = new Array(2);
AnimCycle[0] = Obj1;
AnimCycle[1] = Obj2;
In my code, there are actually 15 objects loaded in the array. I have function that gets called recursively and inside the function, I have this line:
$('#HomeImg').attr('src', AnimCycle[PanelID].ImgSrc);
The problem is that the loading of the image happens when the line is triggered. How can I make the images preload?
Thanks for your suggestions.
Here is a simple script which helps to load images before hand using javascript.
$.each(data, function(index, item) {
var tempImage = new Image();
tempImage.src = item.url;
preloadedImages.push(tempImage);
}
where data as an array of image data
data=
{
name:'NameofImage',
url:'http://www.website.com/image1.jpg',
}
To display the images you can simply add the images to the DOM
$("img").attr({
src: item.src
}).appendTo("#target");
I have a simple jsfiddle which demonstartes the script. It takes data from an ajax request and pre-loads the images. When the user does a mouseover the target it attaches the image to the DOM.
Below is the screenshot showing the images are being loaded at the time the page gets loaded:
this reference link argues that images loaded in div which are hidden might not be pre-loaded in some of the browsers like Opera. I thought haven't verified it.
There might be other ways to load images using css if you do not want to use javascript
Hope this helps
Put all of your images in a hidden div in the html:
<div style="display:none">
<img src="/image1.jpg" />
<img src="/image2.jpg" />
</div>
They will be downloaded when the page loads, but they won't be displayed. Your JavaScript can remain as is.
If you want to do it with script, put this in your ready handler:
var imgPreloader = $("<div>").hide().appendTo("body");
$.each(AnimCycle, function() {
$("<img>").src(this.ImgSrc).appendTo(imgPreloader);
});
Related
Using javascript, I am adding many pixel images, by moving <image id="myimage" xlink:href="mysource.png" ... /> elements from an XMLdoc to the DOM of an SVG image in a loop, like so
var elems = this.XMLdoc.getElementsByTagName('image');
var elem = elems.item(0);
svg.appendChild(elem);
Sometimes not all of the images are completely loaded, due to network problems, or server limitations.
After loading all images, I would like to check whether that has been successful and, if not, reload the pixel image mysource.png.
I could remove and add back all <image> tags and rely on that the cached images are loaded successfully, but then I would still not know if all images were loaded in the second round.
If it was included with <img> in html, I would do this by checking image.complete, but that does not seem to work for the SVG images.
I am also using Snap.svg to manipulate the SVG. A solution based on this library would be convenient if it can help.
In SVG you listen to the load event through the load event, you can do it like this:
var elems = this.XMLdoc.getElementsByTagName('image');
var elem = elems.item(0);
elem.addEventListener("error", replaceImage);
svg.appendChild(elem);
function replaceImage(e){
var parent = this.parentNode;
var newImage = this.cloneNode();
newImage.addEventListener("error", replaceImage);
parent.removeChild(this);
parent.appendChild(newImage);
}
We have a print functionality in our application where we are printing images in the browser. We are dynamically forming the HTML div with all the image sources [image source is from the webservice url]
When we trigger 'Windows.Print()' , only the first image is always available in print preview (chrome) and remaining images are displayed blank.
If i trigger the print event for the second time, all the images are getting printed without any issue because all the images are cached by that time.
Please let me know how to push all my images in cache before printing. I need to do this in javascript. Dont want to make any html change.
I am using backbone.js and creating a model view with the images. Then Binding the view in HTML. Then i ma using for printing. This works fine in IE and Safari. but not in chrome, it shows print preview screen and always trying to load all the images from browser cache. But i will not be having those images in the browser while giving printing. All my images sources are dynamic and coming from the service. I am just setting the url dynamically to the image source.
<%_.each( Documents, function(oDocument) {%>
<div class="images span1">
<img src="<%- oDocument.URL%>" width="98" height="70" />
</div>
<% });%>
in print preview only one image is coming rest all coming as dots. if i cancel the print and give print again all are coming fine.
Thanks,
Jeevitha
This can be done purely in JavaScript by using the Image object.
var cachedImage = new Image();
cachedImage.addEventListener('load', function () {
alert('Cached image loaded');
});
cachedImage.src = 'http://cdn.sstatic.net/stackoverflow/img/apple-touch-icon.png';
I have created a working JSFIDDLE example showing this at http://jsfiddle.net/pwdst/wc1zrL0v/
The new images could be created in response to a user event, for example clicking on a button, or even scrolling past a certain position. If the image from the server has the proper cache headers, it will then be retained in the browser cache for later use in your print page.
You will be able to see the request in the "Network" tab of the Chrome dev tools, or by using the excellent Fiddler tool from Telerik. Successful load will also trigger the load event listener added in the code sample.
I have called the custom function with the array of images i want to cache. Used Jquery 'Deffered' to hold the next operation until all the images are loaded. This is working very fine
var $deferredimages = $.Deferred();
var items = []; // load all the images paths
PreloadImages(items, loadImageitem, function (){
$deferredimages.resolve();
})
function PreloadImages(items, preloadimages, allDone) {
var count = items.length;
// this callback counts down the things to do.
var pendingimages = function (items, i) {
count--;
if (0 == count) {
allDone(items);
}
};
for (var i = 0; i < items.length; i++) {
// 'do' each thing, and await callback.
preloadimages(items, i, pendingimages);
}
}
function loadImageitem(items, i, onComplete) {
var onLoad = function (e) {
e.target.removeEventListener("load", onLoad);
// this next line can be removed.
// only here to prove the image was loaded.
document.body.appendChild(e.target);
// notify that we're done.
onComplete(items, i);
}
var img = new Image();
img.addEventListener("load", onLoad, false);
img.src = items[i];
img.style.visibility = 'hidden';
}
Reference http://jsfiddle.net/8baGb/1/
I show links to 240 images on a page. The real images are uploaded by users. I tried to avoid showing an empty image if users did not upload it yet. jQuery did not work for me because of conflicts, so I have to do it in pure JavaScript.
image(s) links:
<img class="photo240" src="http://www.example.com/i/%%GLOBAL__AuthorID%%/p/b01.jpg" onerror="imgError()">
My JavaScript:
function imgError()
{
alert('The image could not be loaded.');
var _aryElm=document.getElementsByTagName('img'); //return an array with every <img> of the page
for( x in _aryElm) {
_elm=_aryElm[x];
_elm.className="photo240off";
}
}
The style photo240off equals to display:none.
Right now, whenever an image misses, all the images are turned to style photo240off and I want only the missing image to be hidden. So there is something wrong with my script.
(the overall script works well, because I get the alert).
Use this to get the image with the error.
Change to:
onerror="imgError(this)"
Then the function can be:
function imgError(el) {
alert('The image could not be loaded.');
el.className = "photo240off";
}
You need to reference the image from your onerror call and change the class only for that one.
Something like this:
HTML
<img class="photo240" src="example.jpg" onerror="imgError(this)">
JS
function imgError(el) {
el.className="photo240off";
}
I build a website and i want to ask the user when each time visit the site, if he want to display images or not. and if not, i want to do not load them and display the page without any img tag
i tried this, but this is not useful because the page will be loaded
function load_img () {
if (!confirm("Do you want to load the images on your site?")) {
var images = document.getElementsByTagName("img");
var l = images.length;
for (var i=0; i<l; i++) {
images[0].parentNode.removeChild(images[0]);
}
}
}
i need some code that don't load any img tag when the page load,
and not a code that hide or remove the images after the page is loaded and the images are displayed
can someone help me please with this javascript code
thank you
You can take a look at lazyload plugin for jQuery. What this plugin does is load the image when the image is on the visible area of the page.
Their idea is to put the original URL to the image in data-original attribute and in the src attribute put some small image e.g. 1x1 transparent gif like this:
<img data-original=“img/example.jpg” src=“img/grey.gif” />
and then you are able to load all the images whenever you want to just by replacing the the src.
this is a simple javascript code that you can try:
window.onload = function() {
if( confirm('Images?') ) {
var img = document.getElementsByTagName('img');
for(i in img) {
var original = img[i].getAttribute('data-original');
if( original.length ) {
img[i].setAttribute('src', original);
}
}
}
}
You could try jquery : $("img").remove();
It would be better to solve this problem from the server side!
Make start page with a link to a version of the page with images and one without the images. You can write a server side script (PHP?) to show or hide the images. Simple removing the images could break the page design. Also removing html image tags does not do the trick. What about background images, some in css files, ...
If you like to do this an on the client side with javascript you have to remove all images and add them manually with javascript.
Using jQuery you can do:
if (confirm('Hide images?'))
{
$('img').remove();
}
Without jQuery you have to use getElemtentsByTag and a loop.
I have a web page where lots of images called from server using image
scr attribute.
I have created a function like which is triggered by td click.
function GoToStep(stepNo) {
var imgSrc = $("#h1" + stepNo).val();
$(".img_vertical").css("background-image", "url(" + imgSrc + ")");
}
Now the problem is this. For slower connections the images come after some
moment.
Can I pre load images to avoid waiting time when user clicks
td?
I have seen some jquery function to pre load images.
Kindly give some idea how can I achieve it.
Pre-loading an image is equivalent to loading an image but never displaying it. So, you can easily do it like this:
<img src="image.png" alt="" style="display:none;"/>
Now this image will be loaded as soon as the html starts rendering. Whenever you need to use this image as a display or background, just set the address to image.png and it will automatically be fetched from browser's cache.
This can be done using some javascript functions. Quoting from another question.
function preload(arrayOfImages) {
$(arrayOfImages).each(function(){
$('<img/>')[0].src = this;
// Alternatively you could use:
// (new Image()).src = this;
});
}
// Usage:
preload([
'img/imageName.jpg',
'img/anotherOne.jpg',
'img/blahblahblah.jpg'
]);
Explanation of how javascript preloaders work (different question)
[...] The way it works is simply by creating a new Image object and setting
the src of it, the browser is going to go grab the image. We're not
adding this particular image to the browser, but when the time comes
to show the image in the page via whatever method we have setup, the
browser will already have it in its cache and will not go fetch it
again. [...]
So in your case, you should use something like
$(function() {
// Do stuff when DOM is ready
preload([
'img/bg1.jpg',
'img/bg2.jpg',
'img/bg3.jpg'
]);
});