Check if image can be loaded - javascript

I have a page with lots of images on it. My images are loaded from an external server. Usually this server it's loading tooooooooo slow, so my page stay loading until the external server starts running again. I want to put a blank image loaded from mine when the external server is down.
Is there any method to do something like this?
if ($("img").load=false) {
$("img").src="cantload.png";
}
Thank you so much, in advance!

If you're using jquery, and this piece of code happens before the binding of the image.
$("img").error(function() {
alert("Could not load image");
});
If not, then you could do something like this, which will always work, but will need to be on each image:
<img src="image.gif" onerror="alert('Could not load image.')">

If you want to activate this function after the elements are already in the DOM, you can use something like this.
var defaultSource = 'cantload.png';
$('img').each(function() {
var originalSource = $(this).attr('src');
$(this)
.attr('src', defaultSource)
.error(function(){
$(this).attr('src', defaultSource );
})
.attr('src', originalSource);
});
The above code would bind the inner function to handle the images' loading errors, and then make them all reload. The pictures that are already reloaded won't be actually reloaded again, but those with the errors will trigger the error handler and change the source attribute into cantload.png
jsFiddle Demo

Related

jQuery script not working as excepted

I have a jQuery script that should open images full size when they are clicked.
$('img').click( function() {
var src = $(this).attr('src');
window.location.href=src;
});
However, when images are clicked they don't open as expected. Does anyone have any idea why? Any help appreciated :)
Your code seems to work just fine here: http://jsfiddle.net/jfriend00/n6n5R/
So, there is likely some issue with your event handler getting installed properly. Here are things to check:
Are you waiting for the document to load before installing your event handlers?
Are your images dynamically loaded?
Do you have any script errors that are preventing your event handler from running?
For item #1, I would suggest this:
$(document).ready(function() {
$("img").click(function() {
window.location.href = this.src;
});
});
For item #2, you may want to use delegated event handling instead:
$(document).ready(function() {
$(document).on("click", "img", function() {
window.location.href = this.src;
});
});
For item #3, you need to check your browser error console or the debug console and see what script errors might be causing your scripts to stop executing prematurely.
P.S. You may also note that I've simplified your code a bit by just using this.src rather than $(this).attr("src"). No point in using jQuery when it is just longer and slower.
Make sure Jquery is loaded before your script .Also if images are loaded dynamically use this script:
$('body').on('click','img', function() {
var src = $(this).attr('src');
window.location.href=src;
});
Have your images absolute path names? if not, you want to do something like this:
window.location.href = window.location.href.substr(0, window.location.href.lastIndexOf('/')) + src;

load specific image before anything else

I'm a creating a loading screen for website I am making. The website loads many images, scripts, etc. The HTML and CSS part is great, but I need a way to guarantee that the "loading..." image will be loaded before anything else.
I'm using jQuery, and everything is initiated within $(function () { ... });. I imagine that the code for this would need to be called before/outside that block, and the code to remove the loading screen will be called at the very end of that block. Currently, the loading image is set as a DIV background, which is the way I prefer it. However, if it's completely necessary, I will settle for an IMG tag.
Update: (solution)
I was able to answer my own question by using a combination of Robin and Vlad's responses. Both were very good, and excellent answers, however the problem is that they were aimed to load an image before another image, rather than load an image before anything else. (CSS, JS, etc...)
Here's the dirty version of what I came up with:
var files = [new Image(), document.createElement('link'), document.createElement('script')];
files[0].setAttribute('src', 'images/loading.gif');
files[1].setAttribute('rel', 'stylesheet');
files[1].setAttribute('type', 'text/css');
files[1].setAttribute('href', 'test.css');
files[2].setAttribute('type', 'text/javascript');
files[2].setAttribute('src', 'js/jquery-1.5.1.min.js');
window.onload = function (e) {
document.getElementsByTagName('head')[0].appendChild(files[1]);
document.getElementsByTagName('head')[0].appendChild(files[2]);
}
Taking a look at the load sequence on the network tab of Chrome's developer console shows that 'loading.gif' is loaded first, then 4 dummy images, then 'test.css', and then 'jquery.1.5.1.min.js'. The CSS and JS files don't begin to load, until they've been inserted into the head tag. This is exactly what I want.
I'm predicting that I may begin to have some problems, however, when I begin to load a list of files. Chrome reports that sometimes the JS file is loaded first, but the majority of the time the CSS file is loaded first. This isn't a problem, except when I begin to add files to load, I will need to ensure that jQuery is loaded before a script file that uses jQuery.
If anyone has a solution for this, or a way to detect when the CSS/JS files are finished loading, using this method, then please comment. Though, I'm not sure that it's going to be a problem yet. I may need to ask a new question in the future about this, if I start to run into problems.
Thank you to every who has helped with this issue.
Update: (glitch fix)
I ended up running into a lot of problem with this method, because the script files were being loaded asynchronously. If I would clear the browser cache, and then load the page, it would finish loading my jquery dependent files first. Then if I refreshed the page, it would work, because jquery was loaded from cache. I solved this by setting up an array of files to load, then putting the load script into a function. Then I would step through each array item using this code:
element.onload = function() {
++i; _step();
}
element.onreadystatechange = function() {
if (("loaded" === element.readyState || "complete" === element.readyState)) { ++i; _step(); }
}
You can reuse resource prealoding browser support.
I'm not sure it works across all browsers but in my case this approach helps me to load images first. Also it allows to define concrete images so UI specific could be skipped
First define in header what resource you want to preload and define resource priority
<link rel="preload" href="link-to-image" as="image">
or
<link rel="preload" href="link-to-image">
Second line allow to increase loading priority across all object types (scripts / images / styles). First line - only through images.
Then define in body link to image as usual:
<img src="link-to-image" alt="">
Here is my working example
https://jsfiddle.net/vadimb/05scfL58/
As long as the "loading..." image is positioned before any other html elements, it should load first. This of course depends on the size of the image. You could put the loading div right after the tag and position it using 'position:absolute'.
Regarding the code to remove the loading screen, one method is to do the following.
Put all the images, scripts that need to be loaded in a hidden div (display: none)
Set up a variable that will hold the total of the images / scripts to be loaded
Set up a counter variable
Attach to each image / script the "onload" event
Everytime the "onload" event is triggered it will call a function that will increment the counter variable and check if the value of the counter equals the value of the total variable
If all resources have been loaded, fire a custom event that will show the div with the images, and hide the div with the loading screen.
The code below isn't tested so it might not work. Hope it helps
var totalImages = 0;
var loadCounter = 0;
function incrementLoadCounter() {
loadCounter++;
if(loadCounter === totalImages) {
$(document).trigger('everythingLoaded');
}
}
function hideLoadingScreen() {
$('#loadingScreen').hide();
$('#divWithImages').show();
}
$(document).ready(function(e) {
$('#loadingScreen').bind('everythingLoaded', function(e) {
hideLoadingScreen();
});
var imagesToLoad = $('img.toLoad');
totalImages = imagesToLoad.length;
$.each(imagesToLoad, function(i, item) {
$(item).load(function(e) {
incrementLoadCounter();
})
});
})
I'm not sure if it's possible to enforce.
If it is, try adding this in the head-tag:
<script type="text/javascript">
if(document.images)
(new Image()).src="http://www.image.com/example.png";
</script>
In theory that may load and cache that image before anything else.
I think if you place the IMG tag at the top of your html body it will be loaded first. If you do not want to move your div just use a copy of the image tag. Once the images is loaded it will be shown in every image tag which shows the same picture.
Or you could use spin.js as loading image. It display this "loading cycle image" via javascript.
Check it out under:
http://fgnass.github.com/spin.js/

how to display the image at last after loading all the other contents in a webpage

how to display the image at last after loading all the other contents in a webpage.
I've an image on a page which is retrieved from the database when a button is pressed.
I'd like to load entire page first and the image at last after the contents are loaded.
any help?
If by load you mean download the various parts of the page and construct the DOM, then:
$(document).ready(function() {
$('#theimage').show();
});
You can load and add it to your html it in javascript using this function:
$(window).load(function() {
// in 2 steps for clarity, can be optimized
img_html = '<img src="/path/to/image" alt="bla bla" />'; // step 1, generate image html
$("#image_div").append(image_html); // step 2, append image to some div
// optional, see my comment below
$("#image_div img").load(function() {
// triggers when newly added image is completely loaded
});
});
That makes sure loading of the image starts when everything else has finished loading.
Note that the image in the example shows while loading, if you want to load it first and then display it, you'll have to hide it and use the .load event of the image to display it.
$(document).ready(function() {
$('#imageid').attr( "src", "/new/path/to/image.jpg" );
});
In your initial load of the page you can just write a placeholder (div, span, even an image with nothing assigned to it.)
Then attaching to the button click event you can use JQuery + Ajax to callback (not postback, or is there any reason for the postback OTHER than to get the image?) to your server (or a webservice) to get the image path and assign that to the place holder. You can augment that with various jquery animations to "fade in" your image or slide down... what ever you like.
can you use javascript to dynamically set the image url after the dom loaded?
If you have html structure
<image id="image_id"/>
Then use the following jquery code:
$(document).ready(function() {
$("#image_id").attr("src", "link_to_image");
});
Or else, you can use some css trick, hide the image first, so it won't download from server.
Then use the following jquery code to show the image once DOM is ready:
$(document).ready(function() {
$("#image_id").show();
});
At the same time, looks at image preload. this may be useful to you http://www.techrepublic.com/article/preloading-and-the-javascript-image-object/5214317

jQuery to prepend URL in img src attribute

I just need a jQuery snippet to do the prepend in img src , i.e
<img src='/img/picture1.jpg' />
The code snippet jQuery is to prepend this url
http://cdn.something.com/
so after the snippet jQuery, it becomes like
<img src='http://cdn.something.com/img/picture1.jpg' />
Any help is greatly appreciated.
so far I wrote something like
$().ready(function(){
var cdn ='http://cdn.something.com';
$('img').attrib('src', cdn);
});
However it is replaced the src rather than pre
it's not really jQuery related, anyway you could do it with .attr()what is that?:
$('img').attr('src', function(index, src) {
return 'http://cdn.something.com' + src;
});
This would affect all of your <img> nodes in your markup and replace the src.
Anyway, I'm not so sure that this is a great idea. At the time theDOMready event fires, a browser might already have tried to access the old source attribute. If you must do this in Javascript, it's probably a better idea to store the path info within a custom data attribute so a browser is not tempted to load the image. This could look like:
HTML
<img src='' data-path='/img/picture1.jpg' />
JS
$(function() {
$('img').attr('src', function(index, src) {
return 'http://cdn.something.com' + this.getAttribute('data-path');
});
});
This should do it. You could replace this.getAttribute() by $(this).data('path') since jQuery parses those data attributes into it's "node" data hash. But this would create another jQuery object, which really is unecessary at this point.
This should work:
$.ready(function() {
$('img').each(function() {
$(this).attr('src', cdn + $(this).attr('src'));
});
});
However I'm not sure it is the good solution for using a CDN, as the browser will have already tried to load the images from your server at the time the script will be called.
You should do this on the server side instead.
Depending what your specific problem is, you might be able to sort out this problem with a base tag, but I assume you will only want this on images, but changing the src once the page has loaded will make the images reload? IF the images don't exist in the current location you will need to change the src attribute before the page is loaded (server side).

jQuery load-event after replaceWith

i'm trying to ajax load some content and then replace existing content on the page with the newly downloaded content. The problem is that I need to bind load(handler(eventObject)) event for replaced data. I need that to trigger when all images are loaded. Here is what I have so far:
$("#mainContentHolder").live("load", function(){
alert("images loaded!")
});
$.get("content.htm", function(data){
$("#mainContentHolder").replaceWith(data);
alert("content is loaded!");
});
I see an alert when the content is loaded, but it happens before images are loaded and alert on images load never happens (I also tried bind() instead of live() before).
Does anyone know a fix for that?
This may or may not be your problem, but it looks like the container you have attached your image load function to is being replaced when you load the ajax content:
$("#mainContentHolder").live("load", function(){ //you are attaching to current and future '#mainContentHolder' elements
alert("images loaded!")
});
$.get("content.htm", function(data){
$("#mainContentHolder").replaceWith(data); //'#mainContentHolder' element is replaced with something else
alert("content is loaded!");
});
Not sure what content is coming back from your AJAX call, but if it doesn't have a #mainContentHolder element, there will be nothing for your image load event handler to attach to.
If that's not it, there's also this bit: (from http://api.jquery.com/load-event/)
It is possible that the load event will not be triggered if the image is loaded from the browser cache. To account for this possibility, we can use a special load event that fires immediately if the image is ready. event.special.load is currently available as a plugin.
Hopefully one of those will help you out.
Is it possible to put the $.get into the live load function?
$("#mainContentHolder").live("load", function(){
alert("images loaded!");
$.get("content.htm", function(data){
$("#mainContentHolder").replaceWith(data);
alert("content is loaded!");
});
});

Categories