Solved

Detecting if images are loaded (loaded as css background image)

Posted on 2014-03-26
6
6,235 Views
Last Modified: 2014-03-27
Hi E's, I try to get a solution for detect if the images loaded with css background-image were actually loaded:
I try this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="../../ficheiros_apoio/jquery.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style>
#logo{position: relative; background-image: url(image_folder/logo.jpg); width: 50px; height: 50px; background-repeat: no-repeat;}
#home{position: relative; background-image: url(image_folder/home.jpg); width: 50px; height: 50px; background-repeat: no-repeat;}
#contact{position: relative; background-image: url(image_folder/contact.jpg); width: 50px; height: 50px; background-repeat: no-repeat;}
</style>
</head>
<body>
<div id="logo" class="pic"></div>
<div id="home" class="pic"></div>
<div id="contact" class="pic"></div>

<script>
$(document).ready(function(){
jQuery(function($) {
    $(".pic").error(function() {
        var which_fail = $(this).css("background-image");
        alert(which_fail+" fail");
    });
})   
});
</script>
</body>
</html>

Open in new window

But don't work.
It is very important to me because my project for work must have all the images loaded, otherwise the project does not make sense.
Any idea?

The best regards, JC
0
Comment
Question by:Pedro Chagas
  • 2
  • 2
  • 2
6 Comments
 
LVL 82

Accepted Solution

by:
leakim971 earned 315 total points
ID: 39957850
Test page : http://jsfiddle.net/L5e3w/1/

jQuery(function($) { // == $(document).ready(function(){ 
    $(".pic").each(function(i, img) {
        var bi = $(this).css("background-image").match(/url\(["']?([^()]*)["']?\)/).pop();
        var image = new Image();
        $(image).error(function() {
            var which_fail = bi;
            alert(which_fail+" fail");
        });
        $(image).attr("src", bi);
    });  
});

Open in new window

0
 
LVL 30

Assisted Solution

by:Alexandre Simões
Alexandre Simões earned 185 total points
ID: 39958542
I would go for a more javascript native solution by using the onerror event of the image tag.

<img src="http://www.blabla.org/image.png" onerror="onImageError(this)" />
<img src="https://www.google.ch/images/srpr/logo11w.png" onerror="onImageError(this)" />

Open in new window

function onImageError(image){
    alert(image.src);
}

Open in new window


In the onImageError function you can do whatever you want in case there's an error loading the image.

Edit: And for this you also need to rework a bit the layout and use an <img> instead of setting the background image on the div.

Here's a working example: http://jsfiddle.net/AlexCode/8zTvj/

Cheers!
0
 
LVL 30

Assisted Solution

by:Alexandre Simões
Alexandre Simões earned 185 total points
ID: 39958605
I changed the code a bit to allow setting the div's background image but still use the native onerror handlers of the images.

http://jsfiddle.net/AlexCode/8zTvj/1/

Basically I load the image in an <img> tag and on success I set it to the div's background.
As the image is already in the browsers cache it wont get loaded from the server again.

The custom attribute "for" in the <img> element links the image to it's container.

HTML
<div class="hiddenImages">
    <img 
        id="img_dumb"
        for="dumbImageContainer"
        src="http://www.blabla.org/image.png" 
        onerror="onImageError(this)" 
        onload="onImageComplete(this)" />
    <img 
        id="img_google"
        for="googleImageContainer"
        src="https://www.google.ch/images/srpr/logo11w.png" 
        onerror="onImageError(this)"
        onload="onImageComplete(this)" />
</div>

<div id="dumbImageContainer"></div>
<div id="googleImageContainer"></div>

Open in new window


javascript
function onImageError(image){
    var containerId = image.getAttribute("for");
    var container = document.getElementById(containerId);
    container.innerHTML = 'Error!';
}

function onImageComplete(image){
    var containerId = image.getAttribute("for");
    var container = document.getElementById(containerId);
    container.style.backgroundImage = "url(" + image.src + ")";
}

Open in new window


CSS
.hiddenImages{
    display: none;
}

#dumbImageContainer,
#googleImageContainer{
    width: 100px;
    height: 100px;
    border: solid 1px #000;
}

Open in new window

0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
LVL 3

Author Comment

by:Pedro Chagas
ID: 39959807
Hi @leakim971, your solution work good and fits nicely in my code.
Just one question, in your solution $(document).ready function are inside jQuery function, I don't know it is crucial or not for the solution, but have any way to put $(document).ready outside the jQuery function?
That request is because I declare $(document).ready in the begin of my project, and in that project I have a lot of scripts, so I thing is not good idea use $(document).ready two times in my project.

Hi @Alexandre Simões, your solution it is a good solution too, and I believe I will use them in future projects.
At the moment does not fit the way the project is assembled, and would have to make a lot of changes to be able to use your solution. Anyway appreciate it.

The best regards, JC
0
 
LVL 82

Expert Comment

by:leakim971
ID: 39959819
No,

jQuery(function($) is a shortcut of $(document).ready(function(){

you don't need both

to be able to reuse individually part of your code you may have a $(document).ready it more than  one time
0
 
LVL 3

Author Comment

by:Pedro Chagas
ID: 39959915
My apologizes,
I tested your code in "texastic editor" in iPad and I don't saw that it was a comment (// == $(document).ready(function(){).
Thank you.

The best regards, JC
0

Featured Post

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
How to use embargo Date/time in php 29 35
Html5 Index on a table 7 25
JavaScript let vs var 5 21
Show tab when enter div and change underline color 3 18
CSS is a visual language used to classify objects and define rules about how they should be displayed. CSS skills aren’t restricted to developers anymore, there is a big benefit to having a basic understanding of the language, regardless of your occ…
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
In this tutorial viewers will learn how to position overlapping items using z-index in CSS. They will also learn the restrictions on the z-index property.  Create a new HTML document with an internal stylesheet.: Create a div in CSS and name it Red.…
In this tutorial viewers will learn how to style a decorative dropcap for the first letter in a paragraph using CSS. In CSS, create a new paragraph class by typing "p.fancy": Then, to style only the first letter of the first sentence, include the ps…

813 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now