Solved

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

Posted on 2014-03-26
6
5,953 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
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 
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

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Styling your websites can become very complex. Here I'll show how SASS can help you better organize, maintain and reuse your CSS code.
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 customize the background color and font color of highlighted text using the ::selection element in CSS Begin by defining the selected text as an element in CSS by typing "::selection": Style the ::selection…
The viewer will learn the benefit of using external CSS files and the relationship between class and ID selectors. Create your external css file by saving it as style.css then set up your style tags: (CODE) Reference the nav tag and set your prop…

757 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

17 Experts available now in Live!

Get 1:1 Help Now