Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

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

Posted on 2014-03-26
6
Medium Priority
?
7,062 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 1260 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 740 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 740 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
Command Line Tips and Tricks

The command line is a powerful tool at the disposal of every Linux user. Although Linux distros come with beautiful user interfaces, it's worthwhile to learn the command line because it allows you to do a number of things that you otherwise cannot do from the GUI.  

 
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

The top UI technologies you need to be aware of

An important part of the job as a front-end developer is to stay up to date and in contact with new tools, trends and workflows. That’s why you cannot miss this upcoming webinar to explore the latest trends in UI technologies!

Question has a verified solution.

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

Styling your websites can become very complex. Here I'll show how SASS can help you better organize, maintain and reuse your CSS code.
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
In this Micro Tutorial viewers will learn how to create a CSS image sprite (In a later tutorial, viewers will learn how to use CSS and HTML to create a navigation menu using this sprite) Open a new Photoshop document with a width of (Icon width)x(N…
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

721 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