Only load the background-image when it has been fully loaded? - javascript

Well, the title pretty much describes my question:
How to load the background-image dynamically after it has been fully loaded? Sometimes, I must use backgrounds that are so big that it can take a while for the browser to download it. I'd rather 'load it in the background' and let it fade in when it has been fully loaded.
I think jQuery would be best to be using, but I also want my background to appear if JavaScript has been disabled. If this really isn't possible, so be it, but I think it is?
Best regards,
Aart
........
EDIT:
Thanks a bunch, guys! I've been bugged with this for ages and just couldn't think of a nice and easy way.
I converted Jeffrey's Javascript-solution into a jQuery one, just because jQuery's built-in fade looks so awesome.
I'll just post it here in case anyone else has the same issue:
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>
<script type='text/javascript'>
$(document).ready(function() {
$('#img').css('opacity','0').load(function() {
$(this).animate({
opacity: 1
}, 500);
});
});
</script>
<img src='yourimage.jpg' id='img'/>

If the image is included with an img element:
<img src="bg.jpg" id="img" onload="this.style.opacity='1'">
<script>
document.getElementById("img").style.opacity="0";
</script>
That should load the image normally if JavaScript is disabled, but show it only once it loads assuming it's enabled.
One thing to note (that I overlooked): some browsers will not even attempt to load an image if its display property is none. That's why this method uses the opacity attribute.

You can't do it when JS is disabled. However, what you can do is set the background image in CSS and then use the following script (assuming the element has the ID myelem).
(function() {
var elm = document.getElementById('myelem'),
url = 'background image URL here';
elm.style.backgroundImage = "none";
var tmp = new Image();
tmp.onload = function() {
elm.style.backgroundImage = "url('"+url+"')";
// or insert some other special effect code here.
};
tmp.src = url;
})();
EDIT: Although, make sure your background images are optimal. If they are PNG, try having them Indexed with as small a colour table as possible, or make sure the alpha channel is removed if there is no transparency. If they are JPEG, try adjusting the compression.

Check the example on this page:
http://www.w3schools.com/jsref/event_img_onload.asp
Using "image.onload" will start your code only when the image is ready

Without javascript you can't have events, so you won't be able to know if the image is loaded, at least for the first rendering.
You can also use a css preload (put the image as a background in a hidden div), but that would work better in your first refresh and not while loading.

You can set a variable to the image, and when it loads, set it to the body background:
var my_bg = new Image();
my_bg.src = "url(mybackground.png)";
document.style.backgroundImage = my_bg;

What you are looking for is an image onLoad method. If you set the image with a display:none it wont be visible. To get around the possible lack of javascript, you do the following:
<body style="background-image:url(image.png);">
<img src="image.png" style="display:none" onLoad="changeBackground();" />
</body>
<script>
document.body.style.backgroundImage = "";
function changeBackground(){
document.body.style.backgroundImage = "url(image.png)";
}
</script>
This way, if javascript isnt enabled, the bg will load as normal. If it is, it will display at the end

Related

Loading Image sequence in HTML

I have to load image sequence animation about 60 images array. I want this particular sequence loaded separately. means that images loading time does not affected to whole page load time. because it is taking too much time to load page with image sequence animation. Currently i have added all 60 images of sequence in HTML code and set "display:none" to load with page.
Is there any possibility to load this images separately or load after my whole html page loaded. or any other better solution.
Thanks in advance.
Load them dynamically using javascript/jquery
var imagePaths = ["img1.png", ....];
$(document).ready(function(){
for(var i=0; i<imagePaths.length; i++) {
var newImg = $('<img style="display:none;" />'); //Add any class or attribute you want or anything for images.
newImg.bind("load", function(){
$(this).show();
});
newImg.attr("src", imagePaths[i]);
$(parentSelector).append(newImg);
}
});
When you load dynamically from script, your HTML page would have loaded and be ready for use. And later all the images will come into view gradually.
Edit:
In addition if you want to keep your image hidden until it gets completely loaded, you could initially set display:none; inline and attach an onload listener, display:block there.
Hope this helps. Let me know if I missed anything.
Yes it is possible.
var images[60];
var names[60]={"img1.jpg","img2.jpg"...}
function loadImages() {
for(var i=0;i<60;i++) {
images[i] = new Image();
images[i].src = "www.myWebPage.com/"+names[i];
}
}
This function will now load images. Just make sure to call it after your page loads.
<body onLoad="loadImages()">
...
</body>

Dynamically change image src using Jquery not working in IE and firefox

I am implementing a captcha for a email. when click on linkEmail button email modal will open.
there i have to set captcha image generated by a handler (CaptchaGenerator.ashx) on click of linkEmail button click. Here is the code for that.
$(".linkEmail").click(function () {
//Load captcha image
$('.imgCaptcha').attr('src', '/Custom/AppCode/Utilities/CaptchaGenerator.ashx');
$('#emailModal').modal();
});
Above code is working fine in crome but not working in IE and firefox.
Although i have tried followings there is no luck.
HTML:
<p id="captchacontainerp" class="captchacontainer"></p>
-------------------------------------------------------------
$('#captchacontainerp').prepend($("<img id='imCaptcha' class='imgCaptcha' src='/Custom/AppCode/Utilities/CaptchaGenerator.ashx'></img>"));
-------------------------------------------------------------
var img = $('<img id="imCaptcha" class="imgCaptcha">');
img.attr('src', '/Custom/AppCode/Utilities/CaptchaGenerator.ashx');
$('#captchacontainerp').empty();
img.appendTo('#captchacontainerp');
---------------------------------------------------------------
$('#captchacontainerp').empty();
$('#captchacontainerp').append($("<img id='imCaptcha' class='imgCaptcha' src='/Custom/AppCode/Utilities/CaptchaGenerator.ashx'></img>"));
IE caching all GET request, so add a timestamp to your request URL e.g :
$(".linkEmail").click(function () {
//Load captcha image
$('.imgCaptcha').attr('src', '/Custom/AppCode/Utilities/CaptchaGenerator.ashx?'+new Date().getTime());
$('#emailModal').modal();
});
Have you tried setting the src attribute to '' before changing it again?
Also, what are the caching settings you are using (both locally, and on the server)
If you specify any inline style attribute, Height or Width like,
<img src="themes/images/01.png" height="100" width="100" />
<img src="themes/images/01.png" style="height:100px; width=100px;" />
then first remove it and try again.
Even if you externally specify style using style tag,
#imageId{
height : 100px;
width : 100px;
}
then also first remove it and try.
After you remove the style attribute from the images, it will display image.
Height attribute is may work with IE but width attribute not working.
If the above solution doesn't work, then :
Sometime PNG files are not displaying as well. So try to use their JPG image.
I had the same problem when trying to call re captcha button.
After some searching, now function works fine in almost all the famous browsers(chrome,Firefox,IE,Edge,...):
function recaptcha(theUrl) {
$.get(theUrl, function(data, status){});
document.getElementById("captcha-img").src = "";
setTimeout(function(){
document.getElementById("captcha-img").src = "captcha?"+new Date().getTime();
}, 0);
}
'theUrl' is used to render new captcha image and can be ignored in your case. The most important point is generating new URL which forces FF and IE to rerender the image.

Random Background at the Ready

This is really simple, but I'm not a programmer. I just brute force code with general problem solving skills. It's not workin' for this. This code is set to randomize the background image, and it works. However, it's set to wait until the page loads completely, so its timing is too inconsistent. As I understand it, document.ready would give me more consistent (and quicker) timing with it, but I can't seem to make it work. Here's the working version:
<script type="text/javascript">
function changeImg(imgNumber) {
var myImages = [
"http://static.tumblr.com/0obftwk/u0Am8xfjf/streetarturbaninphilade.jpg",
"http://static.tumblr.com/0obftwk/Xmym8xfet/artmuseumarea.jpg",
"http://static.tumblr.com/0obftwk/znNm8xf9e/rowhouseswestphilly.jpg",
"http://static.tumblr.com/0obftwk/af1m8xf87/phillyvista.jpg",
"http://static.tumblr.com/0obftwk/ydIm8xf74/chinagatephiladelphia.jpg",
"http://static.tumblr.com/0obftwk/8kCm8xf41/broadritner.jpg"
];
var imgShown = document.body.style.backgroundImage;
var newImgNumber =Math.floor(Math.random()*myImages.length);
document.body.style.backgroundImage = 'url('+myImages[newImgNumber]+')';
}
window.onload=changeImg;
</script>
If the list of images is known before you load the page, stick the references to your image in the CSS, and then just change the className on document.body
.bgClass1 {background-image: url(http://static.tumblr.com/0obftwk/u0Am8xfjf/streetarturbaninphilade.jpg)}
... and so on...
<body class="bgClass1">
Otherwise, build a preloader with js

jCrop (jQuery) sometimes fails to load image/cropper area

I've got a pretty simple problem, but I've become clueless on what is causing the problem. In one of my applications I'm using jCrop as a small add-on to crop images to fit in banners/headers etc. These steps will be taken:
1) Select an image (using CKFinder for this, CKFinder returns the image path to an input field)
2) Click a button to load the image
3) Crop the image
4) Save the image
in about 75% of the cases everything goes according to plan, however the in the other 25% of the cases jCrop fails to load the cropping area and leaves it blank. Here's the jQuery code I'm using:
jQuery('#selectimg').live('click', function(e) {
e.preventDefault();
var newsrc = jQuery('#img2').val();
jQuery('#cropbox').attr('src', newsrc);
var jcrop_api = jQuery.Jcrop('#cropbox', {
boxWidth: 700,
boxHeight: 700,
onSelect: updateCoords,
onChange: updateCoords
});
//Some other JS code come's here for buttons (they work all the time)
});
I noticed that when I left the part away where #cropbox is being transformd in a cropable area, that the image is loading just fine, so the mistake lies with the var = jcrop_api part, but I slowsly start to think that there is no solution for this...
This is what I've tried so far:
Making a div <div id="cropper-box"></div> and use jQuery('#cropper-box').append('<img src="" id="cropbox" />'); and afterwards set the value. I tried the same thing but setting the image src in 1 step instead of afterwards.
I tried to put a placeholder on the page <img src="placeholder.png" id="cropbox" /> and change the source upon clicking the button. This works, but the cropperarea stays the size of the image (300x180px or something) and doesn't get bigger as it should.
// Edit:
Trying some more showed me that the image source is being replaced properly(! using Firefox to show the source for the selected text), I double checked the URL but this was a correct URL and a working image.
At the place where the cropper should be, there's an about 10x10 pixel white spot where the cropper icon (a plus sign) is popping up.. but as said before: the image isn't shown.
// Edit 2:
So I've took the sources for both the 1st and the 2nd try for the same image. As told before the first try the image won't load properly and the 2nd try it does (only when the 2nd try is the same image(!!)).
The selected page source shows 1 difference which is, first try:
<img style="position: absolute; width: 0px; height: 0px;" src="http://95.142.175.17/uploads/files/Desert.jpg">
second try:
<img style="position: absolute; width: 700px; height: 525px;" src="http://95.142.175.17/uploads/files/Desert.jpg">
I guess this is the image that's being replace by jCrop, but it's a complete riddle why it puts 0 heigth/width in there the first and the proper sizes the second time.
Okay guys, in case anyone else runs into this problem:
jCrop kinda gets messed up if the actions of loading an image and applying jCrop to it are queued too fast after eachother. I still find it strange that a second attempt works perfect, but I think that has something to do with cached image dimensions which are recognized by the DOM of the page or something.
The solution I came up with was by creating a function that converts the #cropbox into a jCrop area and then setting a 2 second interval, just to give jCrop some time to recognize the image and it's dimensions and then convert the element.
This is the part of html I used (with a preloader):
<div id="cropper-loading" style="display: none;"><img src="images/analytics/ajax-loader.gif" /></div>
<img id="cropbox" src="images/placeholder.png" style="display: none;" />
As you can see both the cropbox image and cropper-loading div are hidden as they are not needed instantly. You could display the placeholder if you wanted though.. Then this HTML form is used:
<input name="image2" id="img2" type="text" readonly="readonly" onclick="openKCFinder(this)" value="click here to select an image" style="width: 285px;" /> <button class="button button-blue" type="submit" name="load" id="selectimg">Load Image in cropper</button>
In my case I've been using KCFinder to load the images (it's part of CKEditor, really worth watching into!), KCFinder handles uploads, renaming etc and after choosing it returns the chosen image path (relative/absolute is configurable) to the input field.
Then when clicking #selectimg this code is called:
jQuery('#selectimg').click(function(e) {
e.preventDefault();
jQuery('#cropper-loading').css('display', 'block');
var newsrc = jQuery('#img2').val();
jQuery('#cropbox').attr('src', newsrc);
jQuery('#img').val(newsrc);
function createJcropArea() {
jQuery('#cropper-loading').css('display', 'none');
jQuery('#cropbox').css('display', 'block');
var jcrop_api = jQuery.Jcrop('#cropbox', {
boxWidth: 700,
boxHeight: 700,
onSelect: updateCoords,
onChange: updateCoords
});
clearInterval(interval);
}
var interval = setInterval(createJcropArea, 2000);
});
At first I prevent the link too be followed as it normally would (or button action) and after that the loading div is displayed (that's my reason for hiding the placeholder image, otherwise it would look messed up).
Then the image location is being loaded from the input field and copied into another (#img), this field is used to process the image afterwards (PHP uses the value of #img to load this image). Also simultaneously the #cropbox src is being set to the new image.
And here comes the part which solved my problem:
Instead of directly activating jCrop, I've made a function that:
1) hides the loading icon
2) displays the image
3) converts #cropbox into a jCrop area
4) clean the interval (otherwise it would loop un-ending)
And after this function you can see that, just to be save, I took 2 seconds delay before the jCrop area is being converted.
Hope it helps anyone in the future!
Cheers and thanks for thinking #vector and whoever else did ;-)
Creating an 'Image' object and setting up the 'src' attribute does not apply that you can treat the image like it had already been loaded.
Also, giving any fixed timeout interval does not guaranty the image has already been loaded.
Instead, you should set up an 'onload' callback for the Image Object - which will then initialize the Jcrop Object:
var src = 'https://example.com/imgs/someimgtocrop.jpg';
var tmpImg = new Image();
tmpImg.onload = function() {
//This is where you can safely create an image and a Jcrop Object
};
tmpImg.src = src; //Note that the 'src' attribute is only added to the Image Object after the 'onload' listener was defined
Try the edge library on the repo here: https://github.com/tapmodo/Jcrop
This should solve your problem. The lines that are changed to solve your problem:
// Fix size of crop image.
// Necessary when crop image is within a hidden element when page is loaded.
if ($origimg[0].width != 0 && $origimg[0].height != 0) {
// Obtain dimensions from contained img element.
$origimg.width($origimg[0].width);
$origimg.height($origimg[0].height);
} else {
// Obtain dimensions from temporary image in case the original is not loaded yet (e.g. IE 7.0).
var tempImage = new Image();
tempImage.src = $origimg[0].src;
$origimg.width(tempImage.width);
$origimg.height(tempImage.height);
}
Don't call this function onChange : updateCoords
Try it without and it will run smooth on mobiles.
You can create base64 directly and show them as an image wherever you want.
Here my weird but fantastic solution:
if (obj.tagName == 'IMG') {
var tempImage = new Image();
tempImage.src = $origimg[0].src;
$origimg.width(tempImage.width);
$origimg.height(tempImage.height);
if ($origimg[0].width > 1 && $origimg[0].height > 1) {
$origimg.width($origimg[0].width);
$origimg.height($origimg[0].height);
} else {
var tempImage = new Image();
tempImage.src = $origimg[0].src;
$origimg.width(tempImage.width);
$origimg.height(tempImage.height);
//console.log('error'+$origimg[0].width + $origimg[0].height);
}
I know this is old, but it was happening randomly to my install recently. Found that it was due to images not being full loaded before before jCrop intialized.
All it took to fix it was wrapping the jCrop initialization stuff inside of a
$(window).on("load", function () { //jcrop stuff here });
And it has been working well since.

javascript : simple delayed image show

I'm trying to write a simple javascript snippet which delays the image loading by a certain number of millisecs below.
<html>
<head>
<script type="text/javascript">
function SetTimer()
{
var Timer = setInterval("showImage()",3000);
}
function showImage()
{
document.getElementById('showImage').style.visibility = 'visible';
}
</script>
</head>
<body onLoad="SetTimer()" style="visibility:hidden">
<div id=showImage>
<img src="gwyneth_paltrow_2.jpg">
</div>
</body>
</html>
Am I approaching this incorrectly?
thanks in advance
This is basically an OK approach.
There are some bugs, namely:
document.getElementByID('showImage')style.visibility = 'hidden';
getElementByID should be getElementById
needs a dot after ('showImage')
You are setting the visibility to 'hidden' in order to show it. Instead, you should start out as hidden, and then make it appear instead of disappear.
document.getElementById('showImage').style.visibility = 'hidden';
Well, the code is backwards given the stated goal of delaying the appearance of the image. If I just use your code as a basis, then I would have the visibility of the image as hidden, using CSS, and then trigger the display to visible on the timer.
However, having said that... This doesn't delay the loading of the image, it merely delays the display of it. The other way to handle it is to use the timer to load an Image object in Javascript and then insert it into the DOM. This, then, will actually delay the loading of the image for 3 seconds. Something like this:
function showImage()
{
var myImage = new Image();
myImage.src = "gwyneth_paltrow_2.jpg";
document.getElementById("showImage").appendChild(myImage);
}
I'm doing that from memory, so syntax may not be entirely correct.

Categories