Preload background image - javascript

There's tons of articles of how to preload an image, however I can't seem to find anything useful about preloading a background image with jquery.
I made a simple html mockup of what I'd like to achieve:
http://jsfiddle.net/3rfhr/
A loading div appears
Background is loaded
Loading div disappears
Background DIV appear
I can handle the div transitions but I'm clueless as to how I should go about preloading a css background. Thanks for reading my question :)

You can't as long as it's a background image. Load it normally and then set the background image. Something like this:
var $img = $( '<img src="' + src + '">' );
$img.bind( 'load', function(){
$( '.yourDiv' ).css( 'background-image', 'url(' + src + ')' );
} );
if( $img[0].width ){ $img.trigger( 'load' ); }
the last line is needed in some browser in case the image is cached.

To do the preloading, why not grab the URL from the css attribute with jQuery? Something like this:
var bg_url = jQuery("#DIV-THAT-NEEDS-PRELOADING").css('background-image');
// using regex to replace the " url( ... ) "...
// apologies for my noobish regex skills...
bg_url = str.replace(/ /g, '', bg_url); // whitespace...
bg_url = str.replace(/url\(["']?/g, '', bg_url); // next, the 'url("'...
bg_url = str.replace(/["']?\)/g, '', bg_url); // finally, the trailing '")'...
// without regex, using substring if confident about no quotes / whitespace...
bg_url = bg_url.substring(4, bg_url.length-1);
// preloading...
var img = new Image();
img.onload = function()
{
// do transitions here...
};
img.src = bg_url;

Here's a post from last week that covered preloading images with jQuery: HTML 5 File load image as background-image
And here is the solution that post referenced: http://sveinbjorn.org/dataurls_css

You logic is almost good, but you can not catch events for CSS in jquery.
You need to load the background image to some <img> element. Catch the event load of that element and when it's fired you change the background image to that src and do the rest of your logic.

A working example with a mock setTimeout to simulate loading time.
The relevant jQuery code is:
$('#LOADING-SIGN-DIV').fadeOut();
$('#DIV-THAT-NEEDS-PRELOADING').fadeIn();

Related

Replacing image with jQuery

I have a problem with some image change when clicking on a tab.
Problem is with the arrow image, currently its coming with jQuery like this
$('.toggle_title').prepend('<img class="tab-open" src="my_url" />');
So what I need is that, when the tab is open, image changes itself to "tab-close.png" (flipped arrow). Opened tab has an extra class '.toggle_active' (previous class .toggle_title still stays). I have tried something like this, but its not working, can somebody help?
if($('.toggle_title').hasClass('toggle-active')) {
$('.toggle_active').prepend('<img class="tab-open" src="my_url" />')
}
else {
$('.toggle_title').prepend('<img class="tab-open" src="my_url" />')
}
Working with HTML in strings is an anti-pattern. First create an image element:
// You should NOT hardcode this value, this must come from WordPress,
// but that's for a different topic. See `wp_localize_script` to learn more
// http://codex.wordpress.org/Function_Reference/wp_localize_script
var url = 'http://creativeagency.ee/holi/wp-content/themes/bones/library/images/'
var $img = $('<img>', {
'class': 'tab-open',
src: url +'tab-open.png'
})
Next append the image:
$('.toggle_title').prepend($img);
Now, since you have a reference to image, you can easily change its src attribute when you need:
var $title = $('.toggle_title') // chache your elements!
if($title.hasClass('toggle_active')) { // typo!
$img.attr('src', url +'tab-close.png')
} else {
$img.attr('src', url +'tab-open.png')
}
This should help you out, although it is still probably not the perfect abstraction. You may want to have the possible images in an array, and toggle them a different way:
var srcs = ['tab-close.png','tab-open.png']
$img.attr('src', url + srcs[+$title.is('.toggle_active')])
The above does the same but a bit terser, by casting the boolean to a number, and using is instead of hasClass.

How to detect when -webkit-mask-box-image has downloaded

I generate an mask image on a web server programmatically, then apply it to a HTML element with the following code:
imageToMask.style["-webkit-mask-box-image"] = "url('" + featherURL +"') 100 stretch";
How can I find out when the image comes back and has finished downloading, so that it doesn't just pop onto the page?
You can probably do something similar to what #lonesomeday did in:
jQuery .on() not bound when script inserted into the DOM
Something along these lines:
$('button').click(function() {
var imageToMask = document.createElement('img');
imageToMask.style["-webkit-mask-box-image"] = "url('" + featherURL +"') 100 stretch";
imageToMask.onload = function() {
//Custom behaviour
};
document.body.appendChild(imageToMask);
});

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

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

How do I display a gif animation to the user while a picture is loading (in the web)?

The problem:
I have set of pictures, when the user presses on one of them, it's grow to an area in the page.
The exchange of the pictures is done with the help of js.
Tthe picture is weigh about 0.5M, therefore it's take about 3 sec until the picture is showed.
I would like to present a type of animation while the picture is not displayed.
How can I do this with the help of js?
There's always the "marquee" tag with a "loading" message that you turn off as soon as your image is swapped in. Of course, even I would downvote anyone advocating marquee.
Use the load event, something like:
$("img.something").click(function() {
$(".someDiv").html('<img src="loading.gif"/>');
var $img = $('<img src="bigImage.jpeg" style="display:none"/>');
$img.load(function() {
// once the loading has completed
$(".someDiv").html($(this));
$(this).fadeIn("slow");
});
});
Insert a placeholder element and attach an onload event callback to the <img> element. With jQuery,
var imageElem = $('<img />'),
placeholder = $('<div class="loading">Loading...</div>');
imageElem.attr('src', 'http://example.com/big_image.jpg');
$('#images').append(placeholder).append(imageElem);
imageElem.hide().load(function() {
placeholder.remove();
imageElem.fadeIn();
});

Regular Expression to replace src attribute of img tag

I need a regular expression that will properly work, the current one I have is breaking.
The goal is
Normal src for an image is:
Image.png
Using jQuery on hover I dynamically find the src of an image and replace it with ImageName-Dn.png
On hover off it sets it back to ImageName.png
My current solution:
$(document).ready(function(){
$(".myButton").hover(
function () {
var s = $(this).attr('src');
s = s.substring( 0, s.search(/(\.[a-z]+)$/) ) + '-Dn' + s.match(/(\.[a-z]+)$/)[0];
$(this).attr('src', s);
},
function () {
var o = $(this).attr('src');
o = o.replace(/-Dn\./, '.');
$(this).attr('src', o);
}
);
});
However for some reason the image at some point gets set to ImageName-Dn.png and then screws up and gets set to ImageName-Dn-Dn.png and so on and so forth. Any Help?
A quick fix is to test if the string doesn't already have -Dn in it:
if (!string.match(/-Dn\./))
Also, with the regexes, you don't need to manually split the string and do multiple searches. You can use grouping to receive what you need in a single replace instruction such as:
string.replace(/(.*)\.(.*)/, "$1-Dn.$2")
If you want to read up on regular expressions for Javascript: http://en.wikibooks.org/wiki/JavaScript/Regular_Expressions
are you doing this for a mouseover effect? Why not use image sprites? Effectively, you just need to create 1 image that contains both version of the image side by side and set it to the background of an element which will display it.
for example, a 10x10 image and it's mouseover version will become a 10x20 image with the original on top of the mouseover version.
you can then create a 10x10 div with the background-image set to the 10x20 image. Since only the top 10x10 will be displayed, you only see the original version.
Then in javascript you can simply attach to an event a call to
$(el).style.backgroundPosition = '0px -10px';
on the hover event and
$(el).style.backgroundPosition = '0px 0px';
to reset it
This will shift the background up on the mouse over. Not only is this cleaner than having to deal with regex for a simple image swap, it also reduces the number of files the page has to load.
Hope this helps!
function () {
var s = $(this).attr('src');
if( !s.match(/-Dn\.[a-z]+$/) ) {
s = s.substring( 0, s.search(/(\.[a-z]+)$/) ) + '-Dn' + s.match(/(\.[a-z]+)$/)[0];
$(this).attr('src', s);
}
},
function () {
var o = $(this).attr('src');
o = o.replace(/-Dn\./, '.');
$(this).attr('src', o);
}
(added conditional)

Categories