Solved

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

Posted on 2014-03-26
6
6,462 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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

How our DevOps Teams Maximize Uptime

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

Question has a verified solution.

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

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…
Today, the web development industry is booming, and many people consider it to be their vocation. The question you may be asking yourself is – how do I become a web developer?
In this tutorial viewers will learn how to style transparent/translucent elements using alpha transparency in CSS Start with a normal styled element, such as a div.: Define its "background-color" property as "rgba (255, 255, 255, .5): The numbers in…
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.

735 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