What is the optimum way to handle broken images? - javascript

So there seems to be quiet a few ways to handle broken images on a html page. I would like to know what ways are in popular use and what ways are viewed to be best practice?
To start I've looked at some myself like:
function imgErr(source) {
source.src = /images/missing.jpg";
source.onerror = "";
return true;
}
<img src="test.jpg" alt="test" title="test" onerror="imgErr(this);" />
Pros: works everytime, the event will always be caught. User never sees broken image. Seems to work well across the browsers.
Cons: onerror tag required on each image, function imgErr(source) needs to be in the head to catch the errors, slows down the users experienced load time
$('img').error(function(){
$(this).attr('src', 'missing.jpg');
});
Pros: very little code, works on all images without changing their markup, can be place outside of the head
Cons: can miss the error event depending on the speed of the pages onload event, slows down the users experienced load time
$(window).load(function() {
$("img").each(function() {
if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
var src = $(this).attr("src");
var suffix = src.substring(src.length - 6, src.length).split('.')[0];
suffix = suffix.charAt(suffix.length - 1);
$(this).attr("src", "/static/images/generic/missing_" + suffix + ".jpg");
}
});
});
Pros: Can be placed anywhere on the page, will fix the images no matter when it gets to run, doesn't slow down the users experienced load time
Cons: shows a broken image till it runs creating a poor user experience
In my situation load time is the greatest issue but I can't get the last option to work in IE properly as it changes broken and none broken images alike!
Cheers,
Denis

One thought that does spring to mind is to create an image handler at your web server, i.e.
<img src="fetchimage.aspx?name=test.jpg" alt="test" title="test" />
Ignore the aspx, obviously it'd be replaced with whatever your preferred server scripting technology was. That handler can then deal with image names that aren't present by delivering your missing.jpg for all unknown image names.
Other than that you are stuck with the options you give as far as I can see. Any javascript that runs before the page has loaded risks not iterating over img tags not yet received and any script that waits for page ready is going to risk the user seeing broken images.
Rock->You<-Hardplace

In my opinion, using the alt tag is enough and there's no need to add complexity to the page by checking for it every time using javascript.
Of course you need to check every once in a while that you don't have broken image. There are tools to do it.

Ideally the alt tag should just be used. If this is vital the javascript solution really isn't ideal because it won't work if JS is turned off. You could however do sort of server side solution. Something in php could be done like this but would require a database or some sort of way of setting variables.
<?php
if($image !== ''){?>
<?php echo '<img src="$imgsrc" alt="$imgalt" />' ?>
}
<?php else {
<?php echo '<img src="$imgmissing" alt="$imgalt" />' ?>
} ?>
<?php } ?>

Related

Image load error only fires sometimes

I have a classified style website with 50-100 images per page all loading from different sources at once. Sometimes I get a 404 and I'm trying to handle that.
On each element containing images I have this script:
$el.find('img').one('error', function() {
console.log('broken image detected');
// Replace broken image with something else
}).each(function() {
if(this.complete || $(this).height() > 0){
$(this).load();
}
});
But it seems to fire at random, not picking up all 404 load errors - especially at the beginning of the page where literally none of the 404s are detected. Towards the end of the page it looks a bit better.
What's going on?
I should add, that this piece of JavaScript is not initialised BEFORE the entire DOM has finished loading, but I was under the impression that the .each part would cater for this?
Another idea would be to insert an inline load error detector:
<img src="http://example.com/image.jpg" onerror="window.errorHandler(this);">
But since my JavaScript is modular in design I would prefer to avoid this.
--- EDIT ---
I have solved this problem by inserting an inline script on the onerror handler. It's not super elegant, but it works because the listener is inserted at the same time as the src attribute. Also it is not dependent on jQuery.
I have done a slight work around in my front-end code to cater for this, by exposing a function to window.
All listeners to handle load or error events must be set BEFORE src property of img is setted.
You may implement lazy loading (i.e. insert <img> paths in a data attribute, put a fake pixel in the src attribute, and load the real images on DOM load with jQuery or JavaScript). You then shouldn't face any timing problems.
HTML:
<div id="gallery">
<img id="img1"
src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEAAAAALAAAAAABAAEAAAI="
data-src="imagethatgives404.gif"
width="200" height="200">
<img id="img2"
src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEAAAAALAAAAAABAAEAAAI="
data-src="http://static.jsbin.com/images/dave.min.svg"
width="200" height="200">
</div>
JS:
$(document).ready(function(){
var $el = $('#gallery');
$el.find('[data-src]')
.one('error', function(e) {
console.log(e.target.id + ' is broken');
// Replace broken image with something else
})
.each(function(index,element){
element.src = $(element).data('src');
});
});
The width and height on the <img> tags are used to show how dimensions are preserved.
Example here.

JS - Canvas Image in not working well in chrome ( or how to wait for an image to load properly )

I have a script that draws a QR code with an Image on canvas .
It is using a plugin, and normally - everything works great - but not in chrome .
HTML
<img id="#o99-qrs-img-buffer" src="http://localhost/www.beta.com/logo1.png"
style="display:none">
<div id="o99_qrcode" class="code"></div>
JS script is as follows ( ignore the PHP part - it is working great ):
jQuery(document).ready(function() {
var options = {
render: "'.$qr_render.'", // Canvas, Div ,Image
size: '.$qr_size.',
radius: '. ($qr_corner_r * 0.1) .',
.... tons of other options....
// Image Label -> the problem is here
image: jQuery("#o99-qrs-img-buffer")[0], // taken as example
};
jQuery("#o99_qrcode").empty().qrcode(options);
});
Like said , it is working great on all tested browsers - except in chrome - where it works sporadically . more fail than work. ( 90% - 10% )
Observing a bit , I have noticed two things :
1 - The jQuery(document).ready(function() is not really working as form my understaning of what it should be doing ( and my understanding might be wrong of course ) because the script is firing and displaying the image BEFORE the document is finished to load.
2 - I assume by observing that the script fails becuase ( related to 1 ) - the image is actually nowhere to be found when the script fires - so it has nowhere to take the source from ..
At the beginning I blamed the "display:none" and changed the div to style="width:100px;height:100px;" with jQuery("#o99-qrs-img-buffer").hide(); after the script firing .
No good .
then I tried to change the jQuery(document).ready to load and onLoad.
Still no go .
Reading a LOT of related question here on SE - I found 3 with the hint of my problem : HERE, HERE and HERE.
So I tried to implement the first one , which looked like a solid solution :
var imagetest = new Image();
imagetest.onload = function() {
// wrap the firing in a function only when the image loads
jQuery("#o99_qrcode").empty().qrcode(options);
};
imagetest.src: jQuery("#o99-qrs-img-buffer")[0]; // taken as example
But chrome seems a lot more persistent than me ...
Either I am implementing the solution totally wrong ( very possible ) or I am so unfamiliar with JS that I do not understand the problem at the first place .
The fact that the script working with a plugin seems irrelevant because the plugin works great on all browsers (and sometimes chrome too ..)
At any rate , I need help In finding a way to load the Image and be sure it is loaded before the script fires ...
$(document).ready() is fired, when DOM is fully loaded. In practice this happens at the time when parser have just met </body>. This doesn't mean that the page would be ready/fully loaded, content of external resources like iframes or img might still be loading. $(document).ready() only guarantees you can refer all elements within the HTML.
If you want to wait untill the whole page and all its resources have been completely loaded, you need to use $(window).load().
Also looks like document never triggers load event, $(document).onLoad() doesn't exist.

Is it possible to load an obfuscated html in an iframe content?

I have a doubt. I am having an obfuscated html i want to load that in an iframe component. I want to unobfuscate that before loading it in the iframe component. Is it possible? Is there any javascript tool like that?
Any ideas?
Added a link.
http://colddata.com/developers/online_tools/obfuscator.shtml#obfuscator_view
Original Code:
obfuscated Code:
<script type='text/javascript'>
<!--
var s="=iunm?=cpez?=ejw!dmbtt>#b#?=0ejw?=0cpez?=0iunm?";
m=""; for (i=0; i<s.length; i++) { if(s.charCodeAt(i) == 28){ m+= '&';} else if (s.charCodeAt(i) == 23) { m+= '!';} else { m+=String.fromCharCode(s.charCodeAt(i)-1); }}document.write(m);//-->
</script>
So finally i will be having a file like this but when i am about to load in the iframe component i want to see the real code.
The reason why i want use the obfuscated code is because i will be keeping some static html's in an android device and load those html's since i am keeping it in the device i want to obfuscate. Initially i though of encrypting. But this will cause performance impact.
To load HTML in an iframe with jQuery:
var html = '<div>Your HTML</div>';
$("iframe").contents().find("body").html(html);
The iframe's domain and its parent's must match though.
As for the obfuscation thing, don't do that, if you can un-obfuscate it, everybody can as well.
If you are obfuscating just for the purpose of preventing people from searching the OS quickly for the content, e.g. to hide solutions in a simple game, this would be acceptable on modern devices:
var htmlString = 'this is a test', base64EncodedString = '';
base64EncodedString = window.bToA( htmlString );
You then just need to use the following to reverse:
htmlString = window.aToB( base64EncodedString );
You can then just use Pioul's method for placing it in the iframe.
However as people have stated, obfuscation for other reasons - i.e. proper security protection - is rather pointless, as with a bit of knowledge of your app coders could easily reverse whatever you do (especially as everything involved in the obfuscation is working client-side).

Trying to load an API and a JS file dynamically

I am trying to load Skyscanner API dynamically but it doesn't seem to work. I tried every possible way I could think of and all it happens the content disappears.
I tried console.log which gives no results; I tried elements from chrome's developers tools and while all the content's css remains the same, still the content disappears (I thought it could be adding display:none on the html/body sort of). I tried all Google's asynch tricks, yet again blank page. I tried all js plugins for async loading with still the same results.
Skyscanner's API documentation is poor and while they offer a callback it doesn't work the way google's API's callback do.
Example: http://jsfiddle.net/7TWYC/
Example with loading API in head section: http://jsfiddle.net/s2HkR/
So how can I load the api on button click or async? Without the file being in the HEAD section. If there is a way to prevent the document.write to make the page blank or any other way. I wouldn't mind using plain js, jQuery or PHP.
EDIT:
I've set a bounty to 250 ontop of the 50 I had previously.
Orlando Leite answered a really close idea on how to make this asynch api load although some features doesn't work such as selecting dates and I am not able to set styling.
I am looking for an answer of which I will be able to use all the features so that it works as it would work if it was loading on load.
Here is the updated fiddle by Orlando: http://jsfiddle.net/cxysA/12/
-
EDIT 2 ON Gijs ANSWER:
Gijs mentioned two links onto overwriting document.write. That sounds an awesome idea but I think it is not possible to accomplish what I am trying.
I used John's Resig way to prevent document.write of which can be found here: http://ejohn.org/blog/xhtml-documentwrite-and-adsense/
When I used this method, I load the API successfuly but the snippets.js file is not loading at all.
Fiddle: http://jsfiddle.net/9HX7N/
I belive what you want is it:
function loadSkyscanner()
{
function loaded()
{
t.skyscanner.load('snippets', '1', {'nocss' : true});
var snippet = new t.skyscanner.snippets.SearchPanelControl();
snippet.setCurrency('GBP');
snippet.setDeparture('uk');
snippet.draw(document.getElementById('snippet_searchpanel'));
}
var t = document.getElementById('sky_loader').contentWindow;
var head = t.document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.onreadystatechange= function() {
if(this.readyState == 'complete') loaded();
}
script.onload= loaded;
script.src= 'http://api.skyscanner.net/api.ashx?key=PUT_HERE_YOUR_SKYSCANNER_API_KEY';
head.appendChild(script);
}
$("button").click(function(e)
{
loadSkyscanner();
});
It's load skyscanner in iframe#sky_loader, after call loaded function to create the SearchPanelControl. But in the end, snippet draws in the main document. It's really a bizarre workaround, but it works.
The only restriction is, you need a iframe. But you can hide it using display:none.
A working example
EDIT
Sorry guy, I didn't see it. Now we can see how awful is skyscanner API. It puts two divs to make the autocomplete, but not relative to the element you call to draw, but the document.
When a script is loaded in a iframe, document is the iframe document.
There is a solution, but I don't recommend, is really a workaround:
function loadSkyscanner()
{
var t;
this.skyscanner;
var iframe = $("<iframe id=\"sky_loader\" src=\"http://fiddle.jshell.net/orlleite/2TqDu/6/show/\"></iframe>");
function realWorkaround()
{
var tbody = t.document.getElementsByTagName("body")[0];
var body = document.getElementsByTagName("body")[0];
while( tbody.children.length != 0 )
{
var temp = tbody.children[0];
tbody.removeChild( temp );
body.appendChild( temp );
}
}
function snippetLoaded()
{
skyscanner = t.skyscanner;
var snippet = new skyscanner.snippets.SearchPanelControl();
snippet.setCurrency('GBP');
snippet.setDeparture('uk');
snippet.draw(document.getElementById('snippet_searchpanel'));
setTimeout( realWorkaround, 2000 );
}
var loaded = function()
{
console.log( "loaded" );
t = document.getElementById('sky_loader').contentWindow;
t.onLoadSnippets( snippetLoaded );
}
$("body").append(iframe);
iframe.load(loaded);
}
$("button").click(function(e)
{
loadSkyscanner();
});
Load a iframe with another html who loads and callback when the snippet is loaded. After loaded create the snippet where you want and after set a timeout because we can't know when the SearchPanelControl is loaded. This realWorkaround move the autocomplete divs to the main document.
You can see a work example here
The iframe loaded is this
EDIT
Fixed the bug you found and updated the link.
the for loop has gone and added a while, works better now.
while( tbody.children.length != 0 )
{
var temp = tbody.children[0];
tbody.removeChild( temp );
body.appendChild( temp );
}
For problematic cases like this, you can just overwrite document.write. Hacky as hell, but it works and you get to decide where all the content goes. See eg. this blogpost by John Resig. This ignores IE, but with a bit of work the trick works in IE as well, see eg. this blogpost.
So, I'd suggest overwriting document.write with your own function, batch up the output where necessary, and put it where you like (eg. in a div at the bottom of your <body>'). That should prevent the script from nuking your page's content.
Edit: OK, so I had/took some time to look into this script. For future reference, use something like http://jsbeautifier.org/ to investigate third-party scripts. Much easier to read that way. Fortunately, there is barely any obfuscation/minification at all, and so you have a supplement for their API documentation (which I was unable to find, by the way -- I only found 'code wizards', which I had no interest in).
Here's an almost-working example: http://jsfiddle.net/a8q2s/1/
Here's the steps I took:
override document.write. This needs to happen before you load the initial script. Your replacement function should append their string of code into the DOM. Don't call the old document.write, that'll just get you errors and won't do what you want anyway. In this case you're lucky because all the content is in a single document.write call (check the source of the initial script). If this weren't the case, you'd have to batch everything up until the HTML they'd given you was valid and/or you were sure there was nothing else coming.
load the initial script on the button click with jQuery's $.getScript or equivalent. Pass a callback function (I used a named function reference for clarity, but you can inline it if you prefer).
Tell Skyscanner to load the module.
Edit #2: Hah, they have an API (skyscanner.loadAndWait) for getting a callback once their script has loaded. Using that works:
http://jsfiddle.net/a8q2s/3/
(note: this still seems to use a timeout loop internally)
In the skyrunner.js file they are using document.write to make the page blank on load call back... So here are some consequences in your scenario..
This is making page blank when you click on button.
So, it removes everything from page even 'jQuery.js' that is why call back is not working.. i.e main function is cannot be invoked as this is written using jQuery.
And you have missed a target 'div' tag with id = map(according to the code). Actually this is the target where map loads.
Another thing i have observed is maps is not actually a div in current context, that is maps api to load.
Here you must go with the Old school approach, That is.. You should include your skyrunner.js file at the top of the head content.
So try downloading that file and include in head tag.
Thanks

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/

Categories