I have a website heavily loaded with images. It's quite unattractive to see the images coming up slowly. I've seen a few websites show a preloader which hides that ugly loading phase. I'm not talking about the <img /> tag here, but I'm talking about CSS background-images.
I do not understand how to achieve this effect using JavaScript and/or jQuery.
P.S: I also seeking links to plugins if there are any available.
Start of with setting the css:
#myElement
{
background-image: url('loading.gif');
}
Then use the following javascript function:
function loadImage()
{
var img = new Image;
img.src = "http://path/to/img";
img.onload = function()
{
var myElement = document.getElementById("myElement");
myElement.style.backgroundImage = "url('" + this.src + "')";
}
}
fire the function in the body onload like this:
<body onload="loadImage();">
or add it to another init script which fires from here.
Hope this will get you going!
Related
I don't understand why this function doesn't fire. I want to declare an image in HTML with a single onload function, which will automatically take care of the image's source and mouseover/out functions.
The HTML looks like this:
<img id="menuBtnNovo" onload="imgButton(this)"/>
and the JS function imgButton looks like this:
function imgButton(e){
window.alert("asdasdad");
e.src="images/def/" + e.Id + ".png";
e.onmouseover= function(){ *change image here*}
e.onmouseout= function(){ *change image back here*}
}
Now, not even the alert pops up, and I don't know why. I tried putting script in <head> and setting src to none src="" in the <img>. I'm using Firefox, but it doesn't work in Edge either.
Question is: how do I fire onload function on an image element?
Also, if you have any idea of your own way of implementing this behaviour of automatically loading certain images (that would actually be buttons/links), feel free to share it. I'm new to JS but not to programming.
As you might see, all images are in "images/def/..." and all images for when the mouse is over the img are in "images/mo/...".
I always try and let browser do image replacements, but if you have to use script, than you can do something like this on DOM ready, or window load event:
$('img[data-regular]').each(function(i) {
var thisImage = $(this);
var regular = thisImage.data('regular');
var hover = thisImage.data('hover');
thisImage.attr('src', regular);
/* Preload image for hover */
$('<img/>')[0].src = hover;
/* Set events */
thisImage.on('mouseenter', function(e) {
thisImage.attr('src', hover);
}).on('mouseleave', function(e) {
thisImage.attr('src', regular);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img data-regular="https://placehold.it/350x150" data-hover="https://placehold.it/450x200" />
Also on JSFiddle.
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.
Right now I am building a map of the US, and when you hover over any given state, I am replacing the image with an image of a different color.
My problem is that the way I am currently doing things, the image is being replaced and a new image loaded on hover.
I have the HTML laid out as:
<img class="state" id="alaska" src="img/united-states_Alaska.png" alt="alaska">
<img class="state" id="hawaii" src="img/united-states_hawaii.png" alt="hawaii">
And the jQuery I am using is:
$('.interactive-map img').each(function(e){
var src = $(this).attr('src');
$(this).hover(function(){
$(this).attr('src', src.replace('.png', '-hover.png'));
}, function(){
$(this).attr('src', src);
});
});
I am curious if there is another way to either preload the images with JavaScript, or make it so that there isn't a new request for image every time I hover. I would like to not have to change the HTML or CSS much and optimize it in JavaScript.
Add your images to the DOM on page load but in hidden state, then they get cached
$(function() {
var images = ['url/to/your/jpg1.jpg', 'ur/to/your/png2.png'];
var d = document.createElement("div");
d.style.display = 'none';
document.body.appendChild(d);
for (var i in images)
{
var img = document.createElement("img");
img.src = images[i];
d.appendChild(img);
}
});
Have two image tags and set the first image's display: block. Set the second image's display: none.
Then on hover you switch the them. It is as easy as that.
Use PreloadJS
Example:
var preload = new createjs.LoadQueue();
preload.addEventListener("fileload", handleFileComplete);
preload.loadFile('http://createjs.com/images/404/gBot-confused.jpg');
function handleFileComplete(event) {
document.body.appendChild(event.result);
}
Full Docs: here
Another interesting post using JS and AJAX: Preloading
Thanks for taking some of your time.
I was wondering if there was a possible way using jQuery to trigger a function right after a div background image is finished downloading and rendered.
Let's say you have this div
<div id="img1" class="img1"> </div>
where img1 style is
.img1 {
background-image: some_big_image.png;
background-position:center;
background-repeat:no-repeat;
background-size:cover;
display: none;
}
concidering this javascript function
function showDiv() {
$("#img1").fadeIn(1000);
}
Is there a way to call the previous function right after the image is rendered?
By rendered I mean resized to fit nicely within its div and ready to be shown.
I found a lot of infos about triggering a function after page load or after downloading image but nothing about post-render.
You guys are the bests. Thank you in advance.
Try
var img = new Image();
img.src = "/some_big_image.png";
img.onload = function( ) {
$("#img1").css("background-image", "url('" + img.src + "')" ).fadeIn(1000);
}
Fiddle here
I know you already accepted an answer above, but this can be simplified grealy to just use the jquery magic function
$(function() {
$("#img1").fadeIn(1000);
}
You replied above that the onload event wasn't working for you. The $(function() { //code here } ); fires when the dom is completely ready (not sure if all browsers do this by default for the onload event), so perhaps that is why you were having issues. It is also handy because you can call it multiple places on your page and they will be combined (rather then directly setting onload, which will be overriden if its set somewhere else)
Fiddle here: http://jsfiddle.net/5cR4G/8/
I got a web application, in which there are some images.
Will show a overlay in my page at start and that will automatically fadeout on all images loades.
I need something like this
its rough code
var image1="image1.jpg";
var image2="image2.jpg";
var image4="image4.jpg";
image1 & image2 & image4 loaded then fadeout #preload and show content.
Please help me ... I tried this .. but not working ..
var img1 = new Image();
img1.src = "../images/wall.jpg";
img1.onload = function() {
alert("loaded");
};
var images_loading = $('img').length;
$('img').load(function(){
if(!--images_loading) {
// all images loaded
}
});
Please mind you can't use display:none to hide images.
Using display:none will block image download by your browser. User visibility:hidden instead.
Try this fiddle. I've made it using mostly raw javascript.
If you want, you could use jQuerys .load to replace the onload function, and append to replace appendChild