Javascript load background-image asynchrously - javascript

Is it possible to load a background-image asynchronously?
I've seen many jQuery plugins to load normal image in an asynchronous way, but I can't find if it's possible to preload / asynchronously load a background-image.
EDIT
I clarify my problem. I've been working on this test site http://mentalfaps.com/
The background image is loaded randomly from a set of images refreshed each hour by a chron job (which takes random images on a flickr catalog).
The host is free and slow at the moment, so the background image takes some time to load.
The positioning of the first overlay (the one with the PNG transparent mentalfaps logo) and width are regulated by a function created in the jQuery(document).ready construct.
If you try to refresh the page many times, the width of the right overlay div is 0 (and so you see a "hole" in the layout)
Here is the method to set my positions:
function setPositions(){
var oH = $('#overlay-header');
var overlayHeaderOffset = oH.offset();
var overlayRightWidth = $(window).width() - (overlayHeaderOffset.left + oH.width());
if (overlayRightWidth >= 0) {
$('#overlay-right').width(overlayRightWidth);
} else {
$('#overlay-right').width(0);
}
var lW = $('#loader-wrapper');
lW.offset({
left: (overlayHeaderOffset.left + oH.width() - lW.width())
});
}
The problem is that the $(window).width() is lower then the effective window width! so the check fails and the script goes for $('#overlay-right').width(0);
any ideas?

Not sure whether I really understand your question, but background images (and all other images) are already loaded asynchronously - the browser will start separate requests for them as soon as it encounters the URL while parsing the HTML.
See this excellent answer for background on loading order: Load and execution sequence of a web page?
If you meant something else, please clarify.

The trick to loading something in the background is to load it once, so the next time when it is loaded it already is in the cache.
Put the following at the end of your html:
<script>
var img = new Image();
img.onload = function () {
document.getElementsByTagName('body')[0].style.backgroundImage = 'background.png';
};
img.src = 'background.png';
</script>

You could use a prefetch link in the head.
<link rel="prefetch" href="/images/background.jpg">
You should be able to add these links to the head via JavaScript.

I like to use CSS to fill the background with a color for page load.
After DOM ready event, I use jQuery to modify the CSS and add a background image. That way, the image isn't loaded until after page loads. Not sure about async, but this method gives the user a decent experience.
Example: http://it.highpoint.edu/
The right side navigation links have a background image. The page initializes with a background color. It is replaced with a background image after page load, via jQuery.

changes in this file jquery.ImageOverlay.js
set your height and width and enjoy this...
imageContainer.css({
width : "299px",
height : "138px",
borderColor : hrefOpts.border_color
});

As it is already mentioned, the background image is loaded asynchronously. If you need to load the background image from JQuery code you may also set the addClass() method to set a CSS class or attr("style=\"background-image:url('myimage.png')\"")

Ive found the answer myself, it was a problem due to the .offset() method that gived sometimes the wrong values.
I had the write values using the .position() :
var overlayHeaderOffset = oH.position();

Related

Why is my javascript only working when the part of the page it acts on is visible in the browser?

So I am using the slick image slider and everything was working great until I considered what would happen if images of different heights were put in. I then wrote a short piece of js to check which image is the tallest and set the heights of all of them to that height.
window.onload = imageSlideChange;
$(window).resize(imageSlideChange);
function imageSlideChange(){
var tallestImage = $('.slick-slide').first().height();
$('.slick-slide').each(function(){ //.slick-slide is the class of each image
if($(this).height() > tallestImage){
tallestImage = $(this).height();
}
});
$('.slick-slide').each(function(){
$(this).height(tallestImage);
});
}
The weird thing though is the code only runs correctly when the slider is in the browser window. If I scroll to the bottom or top of the page and reload it will only load the images as 1px height. I thought maybe it was the images not being loaded and set the function to only run on window.loadbut beyond that I don't know what could cause this kind of behavior.
When you go to inspect the images they are the correct height. The 1px must be coming from their default height, which means that when the code runs it must be reading their heights as 0. Why???
If it helps this is all happening as drupal serves up the images, so could that be the problem?

Image resize within the div on manual browser width change

thanks to some external resources and help of some great people the following codepen.io image(post) grid with zoom in effect on hoover was created. There is only one small feature that actually I can't figure out is if for example the user will decide to resize his browser width the images will behaive very very badly, this JS code in some kind destroy responsive behavior of images, but if you refresh the page everything will look nice again.
JS CODE
$(function(){
$('.item-inner').each(function(){
var img = $(this).find('img');
$(this).css({height:img.height(), width:img.width()});
})
})
This code should be put inside a resize() event and also on ready()
function updateImageSize(){
$('.item-inner').each(function(){
var img = $(this).find('img');
$(this).css({height:img.height(), width:img.width()});
})
}
$(window).on('resize',updateImageSize);

jQuery width() is incorrect on load

When I load my page and use $('div.logo').width() it returns a massive value of 6500, which is incorrect. The image is only 130 px wide.
But, if I use a setTimeout and check the $('div.logo').width() after a few seconds it returns the correct width.
Why would this be? All of my CSS should be already loaded so why would the few second pause make a difference?
You have to check the image width after the image has been loaded.
So either:
// NOTE: not $(document).ready
$(window).load(function() {
var width = $('.logo img').width();
});
Or
$('.logo img').load(function() {
var width = $(this).width();
});
should give the right width.
Set the width and height attributes to the image. You can specify the size in CSS too. Then the browser will know what size the image will be before it loads.
That's because an image is not loaded yet, so initial size is based on CSS or guessed. You can use:
$('.logo img').load(function() {
var width = $(this).width();
});
Image is getting loaded with GET method,
so you need to check it after,
$('.logo img').load(function(){
//your code
});
If you want your image gets loaded instantly you may go with BASE64 image.
For more detail Plase see here
it can be javascript modifying the layout of page, for example it can be script tags included on the bottom of the page, or any other javascript code executed on JQuery ready or load events. For example if this code appending html code it can affect width of you .logo div.
Another possibility is that your html is incorrect, to check this simply run any HTML validator like this http://www.freeformatter.com/html-validator.html. When taking HTML from your page for validation, be aware that some browsers fix the incorrect HTML, so better get it from your source code.

Start gif animation not until it's completely loaded

I have a large gif animation on a web page and want to start it not until it's completely finished loading. How would that be possible using JavaScript / jQuery?
Use a placeholder image, and replace it with the animated GIF once that GIF is fully loaded:
<img id="anim" src="placeholder.gif">
JS:
var myanim = new Image();
myanim.src = '/img/actions.png';
myanim.onload = function() {
document.getElementById('anim').src = myanim.src;
}​
http://jsfiddle.net/mblase75/6XTg7/
You can hide GIFs with CSS (or JS replacing them with a placeholder) and when GIFs are loaded you can fire show()
$('img[src$=".gif"]').load(function(){$(this).show())
You could hide it until it is fully loaded.
<!--- this uses jquery !-->
<script type="text/javascript">
var image_url = "http://media.tumblr.com/tumblr_m4doax3R071r9c1z7.gif";
var image = $('<img />').load(function(){
$(this).show();
}).attr('src', image_url).hide();
$('body').append(image);
</script>
The issue here is that once the image has been downloaded (i.e it is in the browsers cache), there really doesn't seem to be any way of starting it from a particular frame.
You have no control over gif animation through javascript, so you have to implement some sort of a hack. You have to make it hidden in the beginning. Instead of the actual picture you can put a div with the dimensions of the actual picture and with text like "wait".
When the image is downloaded in the browser you can substitute div with an image. And at that point of time animation will start

change background image, when big size umage loads

i have a div element, with very big size background image. so, is it possible, to set a little size image as backgrount, untill the big size image loads.
thanks
I guess you could put another div element underneath it (using the z-index property) and give that the faster loading background image.
Whether that is practical to do, depends on your Layout, you'd have to give more information about that.
There's also the ages-old lowsrc HTML 4 property that still seems to be pretty well supported (I have not tried it myself since Netscape 4), but that won't work for background images.
CSS:
.that-div {
background-image:url(/path/to/small-image.png);
}
jQuery:
$(function () {
var bigImg = new Image(),
bigImgSrc = '/path/to/big-image.png';
bigImg.src = bigImgSrc;
$(bigImg).load(function(){
$('.that-div').css('background-image':'url('+bigImgSrc+')');
});
});

Categories