I want to set a background image on the body tag, then run some code - like this:
$(\'body\').css(\'background-image\',\'http://picture.de/image.png\').load(
Here is a simple vanilla hack ~
(function(image){
image.onload = function(){
$(body).addClass('loaded-background');
alert('Background image done loading');
// TODO fancy fade-in
};
image.src = "http://picture.de/image.png";
})(new Image());
There are no JS callbacks for CSS assets.
Something like this:
var $div = $('div'),
bg = $div.css('background-image');
if (bg) {
var src = bg.replace(/(^url\()|(\)$|[\"\'])/g, ''),
$img = $('<img>').attr('src', src).on('load', function() {
// do something, maybe:
$div.fadeIn();
});
}
});
Here is a small plugin I made to allow you to do exactly this, it also works on multiple background images and multiple elements:
Read the article:
http://catmull.uk/code-lab/background-image-loaded/
or go straight to the plugin code:
http://catmull.uk/downloads/bg-loaded/bg-loaded.js
So just include the plugin and then call it on the element:
<script type="text/javascript" src="http://catmull.uk/downloads/bg-loaded/bg-loaded.js"></script>
<script type="text/javascript">
$('body').bgLoaded();
</script>
Obviously download the plugin and store it on your own hosting.
By default it adds an additional "bg-loaded" class to each matched element once the background is loaded but you can easily change that by passing it a different function like this:
<script type="text/javascript" src="http://catmull.uk/downloads/bg-loaded/bg-loaded.js"></script>
<script type="text/javascript">
$('body').bgLoaded({
afterLoaded : function() {
alert('Background image done loading');
}
});
</script>
Here is a codepen demonstrating it working.
http://codepen.io/catmull/pen/Lfcpb