Avoid wrong interpretation of source with document.createElement for dynamic sources - javascript

I have script that I would like visitors on my website to run when they load a web page. It looks like this:
window.onload = function(){
var pxl=document.createElement('img');
pxl.setAttribute('src', 'http://localhost:8080/getTrackingPixel')
document.body.appendChild(pxl);
}
Most of the times the source returns an image and it works fine. However, sometimes it returns this:
<html><body style="background-color:transparent"></body></html>
And I can't really change the fact that it might sometimes not return an image. How do I change the javascript so that it can handle the html response without any errors? It might be possible for me to predict when it happens though - but I haven't managed to find a good way to request the source and return the html either.

You can achieve it by using the javascript Image object which, unlike the createElement approach, allows you to fetch the src url before inserting the img in the DOM.
The onload event of the Image object won't fire if the loaded content isn't an img.
Here it is :
window.onload = function(){
var pxl = new Image();
pxl.onload = function(){
// is IMG
document.body.appendChild(pxl);
}
pxl.onerror = function(){
// is not IMG
// Meaning in your case : <html><body style="background-color:transparent"></body></html>
}
pxl.src = 'http://localhost:8080/getTrackingPixel';
}
(Note that your code also missed the semicolon ";" line 4)

Related

How to choose first working image source from array in React.js [duplicate]

I'm using JavaScript with the jQuery library to manipulate image thumbnails contained in a unordered list. When the image is loaded it does one thing, when an error occurs it does something else. I'm using jQuery load() and error() methods as events. After these events I check the image DOM element for the .complete to make sure the image wasn't already loaded before jQuery could register the events.
It works correctly except when an error occurs before jQuery can register the events. The only solution I can think of is to use the img onerror attribute to store a "flag" somewhere globally (or on the node it's self) that says it failed so jQuery can check that "store/node" when checking .complete.
Anyone have a better solution?
Edit: Bolded main points and added extra detail below:
I'm checking if an image is complete (aka loaded) AFTER I add a load and error event on the image. That way, if the image was loaded before the events were registered, I will still know. If the image isn't loaded after the events then the events will take care of it when it does. The problem with this is, I can easily check if an image is loaded already, but I can't tell if an error occurred instead.
Check the complete and naturalWidth properties, in that order.
https://stereochro.me/ideas/detecting-broken-images-js
function IsImageOk(img) {
// During the onload event, IE correctly identifies any images that
// weren’t downloaded as not complete. Others should too. Gecko-based
// browsers act like NS4 in that they report this incorrectly.
if (!img.complete) {
return false;
}
// However, they do have two very useful properties: naturalWidth and
// naturalHeight. These give the true size of the image. If it failed
// to load, either of these should be zero.
if (img.naturalWidth === 0) {
return false;
}
// No other way of checking: assume it’s ok.
return true;
}
Another option is to trigger the onload and/or onerror events by creating an in memory image element and setting its src attribute to the original src attribute of the original image. Here's an example of what I mean:
$("<img/>")
.on('load', function() { console.log("image loaded correctly"); })
.on('error', function() { console.log("error loading image"); })
.attr("src", $(originalImage).attr("src"))
;
Based on my understanding of the W3C HTML Specification for the img element, you should be able to do this using a combination of the complete and naturalHeight attributes, like so:
function imgLoaded(imgElement) {
return imgElement.complete && imgElement.naturalHeight !== 0;
}
From the spec for the complete attribute:
The IDL attribute complete must return true if any of the following
conditions is true:
The src attribute is omitted.
The final task that is queued by the networking task source once the resource has been fetched has been queued.
The img element is completely available.
The img element is broken.
Otherwise, the attribute must return false.
So essentially, complete returns true if the image has either finished loading, or failed to load. Since we want only the case where the image successfully loaded we need to check the nauturalHeight attribute as well:
The IDL attributes naturalWidth and naturalHeight must return the
intrinsic width and height of the image, in CSS pixels, if the image
is available, or else 0.
And available is defined like so:
An img is always in one of the following states:
Unavailable - The user agent hasn't obtained any image data.
Partially available - The user agent has obtained some of the image data.
Completely available - The user agent has obtained all of the image data and at least the image dimensions are available.
Broken - The user agent has obtained all of the image data that it can, but it cannot even decode the image enough to get the image
dimensions (e.g. the image is corrupted, or the format is not
supported, or no data could be obtained).
When an img element is either in the partially available state or in
the completely available state, it is said to be available.
So if the image is "broken" (failed to load), then it will be in the broken state, not the available state, so naturalHeight will be 0.
Therefore, checking imgElement.complete && imgElement.naturalHeight !== 0 should tell us whether the image has successfully loaded.
You can read more about this in the W3C HTML Specification for the img element, or on MDN.
I tried many different ways and this way is the only one worked for me
//check all images on the page
$('img').each(function(){
var img = new Image();
img.onload = function() {
console.log($(this).attr('src') + ' - done!');
}
img.src = $(this).attr('src');
});
You could also add a callback function triggered once all images are loaded in the DOM and ready. This applies for dynamically added images too. http://jsfiddle.net/kalmarsh80/nrAPk/
Use imagesLoaded javascript library.
Usable with plain Javascript and as a jQuery plugin.
Features:
officially supported by IE8+
license: MIT
dependencies: none
weight (minified & gzipped) : 7kb minified (light!)
Resources
Project on github: https://github.com/desandro/imagesloaded
Official website: http://imagesloaded.desandro.com/
https://stackoverflow.com/questions/26927575/why-use-imagesloaded-javascript-library-versus-jquerys-window-load
imagesloaded javascript library: what is the browser & device support?
Retrieve informations from image elements on the page
Test working on Chrome and Firefox
Working jsFiddle (open your console to see the result)
$('img').each(function(){ // selecting all image element on the page
var img = new Image($(this)); // creating image element
img.onload = function() { // trigger if the image was loaded
console.log($(this).attr('src') + ' - done!');
}
img.onerror = function() { // trigger if the image wasn't loaded
console.log($(this).attr('src') + ' - error!');
}
img.onAbort = function() { // trigger if the image load was abort
console.log($(this).attr('src') + ' - abort!');
}
img.src = $(this).attr('src'); // pass src to image object
// log image attributes
console.log(img.src);
console.log(img.width);
console.log(img.height);
console.log(img.complete);
});
Note : I used jQuery, I thought this can be acheive on full javascript
I find good information here OpenClassRoom --> this is a French forum
After reading the interesting solutions on this page, I created an easy-to-use solution highly influenced by SLaks' and Noyo's post that seems to be working on pretty recent versions (as of writing) of Chrome, IE, Firefox, Safari, and Opera (all on Windows). Also, it worked on an iPhone/iPad emulator I used.
One major difference between this solution and SLaks and Noyo's post is that this solution mainly checks the naturalWidth and naturalHeight properties. I've found that in the current browser versions, those two properties seem to provide the most helpful and consistent results.
This code returns TRUE when an image has loaded fully AND successfully. It returns FALSE when an image either has not loaded fully yet OR has failed to load.
One thing you will need to be aware of is that this function will also return FALSE if the image is a 0x0 pixel image. But those images are quite uncommon, and I can't think of a very useful case where you would want to check to see if a 0x0 pixel image has loaded yet :)
First we attach a new function called "isLoaded" to the HTMLImageElement prototype, so that the function can be used on any image element.
HTMLImageElement.prototype.isLoaded = function() {
// See if "naturalWidth" and "naturalHeight" properties are available.
if (typeof this.naturalWidth == 'number' && typeof this.naturalHeight == 'number')
return !(this.naturalWidth == 0 && this.naturalHeight == 0);
// See if "complete" property is available.
else if (typeof this.complete == 'boolean')
return this.complete;
// Fallback behavior: return TRUE.
else
return true;
};
Then, any time we need to check the loading status of the image, we just call the "isLoaded" function.
if (someImgElement.isLoaded()) {
// YAY! The image loaded
}
else {
// Image has not loaded yet
}
Per giorgian's comment on SLaks' and Noyo's post, this solution probably can only be used as a one-time check on Safari Mobile if you plan on changing the SRC attribute. But you can work around that by creating an image element with a new SRC attribute instead of changing the SRC attribute on an existing image element.
Realtime network detector - check network status without refreshing the page:
(it's not jquery, but tested, and 100% works:(tested on Firefox v25.0))
Code:
<script>
function ImgLoad(myobj){
var randomNum = Math.round(Math.random() * 10000);
var oImg=new Image;
oImg.src="YOUR_IMAGELINK"+"?rand="+randomNum;
oImg.onload=function(){alert('Image succesfully loaded!')}
oImg.onerror=function(){alert('No network connection or image is not available.')}
}
window.onload=ImgLoad();
</script>
<button id="reloadbtn" onclick="ImgLoad();">Again!</button>
if connection lost just press the Again button.
Update 1:
Auto detect without refreshing the page:
<script>
function ImgLoad(myobj){
var randomNum = Math.round(Math.random() * 10000);
var oImg=new Image;
oImg.src="YOUR_IMAGELINK"+"?rand="+randomNum;
oImg.onload=function(){networkstatus_div.innerHTML="";}
oImg.onerror=function(){networkstatus_div.innerHTML="Service is not available. Please check your Internet connection!";}
}
networkchecker = window.setInterval(function(){window.onload=ImgLoad()},1000);
</script>
<div id="networkstatus_div"></div>
This is how I got it to work cross browser using a combination of the methods above (I also needed to insert images dynamically into the dom):
$('#domTarget').html('<img src="" />');
var url = '/some/image/path.png';
$('#domTarget img').load(function(){}).attr('src', url).error(function() {
if ( isIE ) {
var thisImg = this;
setTimeout(function() {
if ( ! thisImg.complete ) {
$(thisImg).attr('src', '/web/css/img/picture-broken-url.png');
}
},250);
} else {
$(this).attr('src', '/web/css/img/picture-broken-url.png');
}
});
Note: You will need to supply a valid boolean state for the isIE variable.
var isImgLoaded = function(imgSelector){
return $(imgSelector).prop("complete") && $(imgSelector).prop("naturalWidth") !== 0;
}
// Or As a Plugin
$.fn.extend({
isLoaded: function(){
return this.prop("complete") && this.prop("naturalWidth") !== 0;
}
})
// $(".myImage").isLoaded()
As I understand the .complete property is non-standard. It may not be universal... I notice it seem to work differently in Firefox verses IE. I am loading a number of images in javascript then checking if complete. In Firefox, this seems to work great. In IE, it doesn't because the images appear to be loading on another thread. It works only if I put a delay between my assignment to image.src and when I check the image.complete property.
Using image.onload and image.onerror isn't working for me, either, because I need to pass a parameter to know which image I am talking about when the function is called. Any way of doing that seems to fail because it actually seems to pass the same function, not different instances of the same function. So the value I pass into it to identify the image always ends up being the last value in the loop. I cannot think of any way around this problem.
On Safari and Chrome, I am seeing the image.complete true and the naturalWidth set even when the error console shows a 404 for that image... and I intentionally removed that image to test this. But the above works well for Firefox and IE.
This snippet of code helped me to fix browser caching problems:
$("#my_image").on('load', function() {
console.log("image loaded correctly");
}).each(function() {
if($(this).prop('complete')) $(this).load();
});
When the browser cache is disabled, only this code doesn't work:
$("#my_image").on('load', function() {
console.log("image loaded correctly");
})
to make it work you have to add:
.each(function() {
if($(this).prop('complete')) $(this).load();
});
Using this JavaScript code you can check image is successfully loaded or not.
document.onready = function(e) {
var imageobj = new Image();
imageobj.src = document.getElementById('img-id').src;
if(!imageobj.complete){
alert(imageobj.src+" - Not Found");
}
}
Try out this
I had a lot of problems with the complete load of a image and the EventListener.
Whatever I tried, the results was not reliable.
But then I found the solution. It is technically not a nice one, but now I never had a failed image load.
What I did:
document.getElementById(currentImgID).addEventListener("load", loadListener1);
document.getElementById(currentImgID).addEventListener("load", loadListener2);
function loadListener1()
{
// Load again
}
function loadListener2()
{
var btn = document.getElementById("addForm_WithImage"); btn.disabled = false;
alert("Image loaded");
}
Instead of loading the image one time, I just load it a second time direct after the first time and both run trough the eventhandler.
All my headaches are gone!
By the way:
You guys from stackoverflow helped me already more then hundred times. For this a very big Thank you!
This one worked fine for me :)
$('.progress-image').each(function(){
var img = new Image();
img.onload = function() {
let imgSrc = $(this).attr('src');
$('.progress-image').each(function(){
if($(this).attr('src') == imgSrc){
console.log($(this).parent().closest('.real-pack').parent().find('.shimmer').fadeOut())
}
})
}
img.src = $(this).attr('src');
});

updating image source using jquery not working properly

I'm trying to update my image source using jquery. To do it, I am calling .load
function that will return a string which in turn will be used to replace the image source.
srcResult value is new/icon.png:
<script>
var iconLinkURL = "Users/NewIcon";
var srcResult = $("#iconImage").children('img').load(iconLinkURL);
$("#iconImage").children('img').attr('src', srcResult);
</script>
HTML Side
<a id="iconImage"><img src="old/address.png"></img></a>
What happens is that when the javascript is loaded, the image is loaded like this:
<a id="iconImage"><img src="[object Object]">new/icon.png</img></a>
Am I missing something hence the issue is persisting?
load() returns an object. If you're not interested in pre-loading, just replace your code as follows:
$("#iconImage").children('img').prop('src', 'Users/NewIcon');
However, if you wish to preload the image, use the following:
var src = 'Users/NewIcon',
img = new Image();
img.src = src;
img.onload = function() {
$('#iconImage').children('img').prop('src', this.src);
};
It's worth noting that you will also need to wrap your code in the DOMReady event if you're not doing that already.

Image loading time

When I click on my website sometimes you can visually see the images slowly loading into the place. I don't really like this and if possible would like to prevent it from happening.
From reading round it seems preloading images is the solution I'm looking for? Let me know if that's correct or if there is a better way.
On this forum I see lots of answers to preloading images and below is a code I think works but I want to change it slightly:
var preloadImages = [ img/1.jpg,img/2.jpg];
for(var i = 0 ; i < preloadImages.length; i++) {
new Image().src = preloadImages[i];
}
I think this code above works but it requires me to type in every image source into an array. On my website there are lots of images and I will probably continue to add more. So is there a way to push all the image sources into the array without actually typing them in. So as I add more images the preloading take care of itself.
If you wanted to go down the route you already have you could search the entire DOM for tags first and then add them to the array.
Perhaps something along these lines:
images = []
$(body).find('img').each ->
imgSrc = $(this).attr('src')
image.push imgSrc
i = 0
while i < preloadImages.length
(new Image).src = preloadImages[i]
i++
That will need jQuery and probably some tweaking. I can't imagine this being the best approach however as you still need to wait for the DOM, then jQuery to load and then run through the entire DOM with the function(s).
If the issue is more that the content is moving around you can (and probably should) prevent this by giving the tag itself a height and width if you know it in advance.
Additionally it's always worth optimizing your images (either by hand or on build/compile using something like Gulp.js) if you haven't already. It's incredible how much you can reduce load times by simply by using the optimal image (in terms of size and format).
You can call below function after page load
function preloadImages(){
$('img').each(function(){
new Image().src = this.src;
});
}
You can use this function to set multiple after-page-load functions
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = function(){
func();
};
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
};
}
}
then add your function like this
addLoadEvent(preloadImages);
But I don't think you can really pre-load images like this. To really pre-load images, you have to start loading those images as soon as your DOM starts to render on the client-side. And that means loading them in the head section. But if you do that, because you don't have your html just yet, you will not be able to run the above function, because it needs the DOM to be fully downloaded. You have to hardcode your image sources into javascript like you already did, and put your function as the first thing in the head section.

Load list of images in sequential order

I'm working on a website which uses ExpressionEngine to create a list of images with img1, img2, img3 etc as the ID and creates an array with their sources imgAddresses[1], imgAddresses[2], imgAddresses[3] etc.
I'm attempting to create a function which loads the first image, then (when the first is completely loaded), load the second, third etc. The following is what I have so far:
function loadImage(counter) {
var i = document.getElementById("img"+counter);
if(counter==imgAddresses.length) { return; }
i.onload = function(){
loadImage(counter+1)
};
i.src = imgAddresses[counter];
}
document.onload=loadImage(0);
It works when refreshing the page, but not when accessing the page via the URL. As far as I can tell from research, this is because the onload event is not fired when a cached image is loaded, and refreshing the page clears the cache, whereas accessing the page via the URL does not.
Research suggests that assigning the src of the image after declaring the onload event would get around this, but it does not seem to have solved it in this case. I was thinking that this may be because the onload event is recursive in this case.
Does anyone have any ideas on how to make sure the browser is loaded a fresh copy of the image, rather than a cached version? Or whether there is a better way to write this function? Thanks for any help!
EDIT: One solution that I have found is to change the img source assignment to:
i.src = imgAddresses[counter] + '?' + new Date().getTime();
This forces the user to load a fresh copy each time, which I guess is not so much a solution, but a workaround
The only thing I can say is that you are not attaching the document.onload handler correctly. I cannot tell if it will fix your issue because image.onload is not reliable in all browsers, however the onload should be set to a function reference and that's not what you are doing.
Instead, you should have something like:
function loadImage(counter) {
//initialize the counter to 0 if no counter was passed
counter = counter || 0;
var i = document.getElementById("img"+counter);
if(counter==imgAddresses.length) { return; }
i.onload = function(){
loadImage(counter+1)
};
i.src = imgAddresses[counter];
}
document.onload = loadImage; //instead of loadImage(0);
You can tell how the browser will manage the cached resources
Take a look to HTML5 cache approach:
HTML5: The cache manifest file
This way you can avoid the browser cache for the specified resources.

How does the javascript preloading work?

I don't want to know a way to preload images, I found much on the net, but I want to know how it works.
How is javascript able to preload images?
I mean, I tried a snippet from here, and even if it works, it doesn't seem to preload images.
When I check firebug, I can see that the image is loaded twice, once while the preloading, another time when displaying it!
To improve this code I'd like to know how it works.
Here is what i do:
function preload(arrayOfImages) {
$(arrayOfImages).each(function(){
$('<img/>')[0].src = this;
//(new Image()).src = this;
alert(this +' && ' + i++);
});
}
then i do something like that:
preloader = function() {
preload(myImages);
}
$(document).ready(preloader);
Here is how i display/add the image :
$("li.works").click(function() {
$("#viewer").children().empty();
$('#viewer').children().append('<img src=\'images/ref/'+this.firstChild.id+'.jpg\' alt="'+this.firstChild.id+'" \/>')
$("#viewer").children().fadeIn();
Your basic Javascript preloader does this:
var image = new Image();
image.src = '/path/to/the/image.jpg';
The way it works is simply by creating a new Image object and setting the src of it, the browser is going to go grab the image. We're not adding this particular image to the browser, but when the time comes to show the image in the page via whatever method we have setup, the browser will already have it in its cache and will not go fetch it again. I can't really tell you why whatever you have isn't working this way without looking at the code, though.
One interesting gotcha that is discussed in this question is what happens when you have an array of images and try preloading them all by using the same Image object:
var images = ['image1.jpg','image2.jpg'];
var image = new Image();
for(var x = 0; x < images.length; x++) {
image.src = images[x];
}
This will only preload the last image as the rest will not have time to preload before the loop comes around again to change the source of the object. View an example of this. You should be able to instantly see the second image once you click on the button, but the first one will have to load as it didn't get a chance to preload when you try to view it.
As such, the proper way to do many at once would be:
var images = ['image1.jpg','image2.jpg'];
for(var x = 0; x < images.length; x++) {
var image = new Image();
image.src = images[x];
}
Javascript preloading works by taking advantage of the caching mechanism used by browsers.
The basic idea is that once a resource is downloaded, it is stored for a period of time locally on the client machine so that the browser doesn't have to retrieve the resource again from across the net, the next time it is required for display/use by the browser.
Your code is probably working just fine and you're just misinterpeting what Fire Bug is displaying.
To test this theory just hit www.google.com with a clean cache. I.e. clear your download history first.
The first time through everything will likely have a status of 200 OK. Meaning your browser requested the resource and the server sent it. If you look at the bottom on the Fire Bug window it will says how big the page was say 195Kb and how much of that was pulled from cache. In this case 0Kb.
Then reload the same page without clearing your cache, and you will still see the same number of requests in FireBug.
The reason for this is simple enough. The page hasn't changed and still needs all the same resources it needed before.
What is different is that for the majority of these requests the server returned a 304 Not Modified Status, so the browser checked it's cache to see if it already had the resource stored locally, which in this case it did from the previous page load. So the browser just pulled the resource from the local cache.
If you look at the bottom of the Fire Bug window you will see that page size is still the same (195Kb) but that the majority of it, in my case 188Kb, was pulled locally from cache.
So the cache did work and the second time i hit Google I saved 188Kb of download.
I'm sure you will find the same thing with preloading your images. The request is still made but if the server returns a status of 304 then you will see that the image is in fact just pulled from local cache and not the net.
So with caching, the advantage is NOT that you kill off all future resource requests, i.e. a Uri lookup is still made to the net but rather that if possible the browser will pull from the local cache to satisify the need for the content, rather than run around the net looking for it.
You may be confused by the concept of "preloading". If you have a bunch of images in your HTML with <img src="...">, they cannot be preloaded with Javascript, they just load with the page.
Preloading images with Javascript is about loading images not already in the document source, then displaying them later. They are loaded after the page has rendered for the first time. They are preloaded in order to eliminate/minimize loading time when it comes to making them appear, for example when changing an image on mouse rollover.
For most applications, it is usually better practice to use "CSS sprites" as a form of preloading, in lieu of Javascript. SO should have a ton of questions on this.
It just involves making a new DOM image object and setting the src attribute. Nothing clever and AFAIK, it has always worked for me.
Is it possible the second "load" firebug is showing you is it loading it from cache?
The index on the loop is only looking
at the first image. Change it to use
the index:
function preload(arrayOfImages) {
$(arrayOfImages).each(function(i){ // Note the argument
$('<img/>')[i].src = this; // Note the i
//(new Image()).src = this;
alert(this +' && ' + i++);
});
}
Edit: In retrospect, this was wrong and I can see you're trying to create image elements. I don't understand why the index is there at all, there need not be an index. I think the function should look like this:
function preload(arrayOfImages) {
$(arrayOfImages).each(function () {
$('<img/>').attr('src', this);
});
}
And to instantiate it, why not just do this:
$(function () { // Equivalent to $(document).ready()
preload(myImages);
});
JavaScript image preloading works because when a DOM element that contains an image is created, the image is downloaded and cached. Even if another request is made when the image is actually rendered from the HTML, the server will send back a 304 (not changed), and the browser will simply load the image from its cache.
Paolo suggests using the following notation to create an image object:
var image = new Image();
While this will work, the DOM-compliant way of doing this is:
var image = document.createElement('img');
image.setAttribute('src', 'path/to/image.jpg');
Which is the way it is being done in the script, except it's using jQuery's HTML string literal syntax to do it. Additionally, most modern browsers offer compatibility with the Image() constructor by simply calling DOM-standard methods. For example, if you open up the Google Chrome JavaScript console and type Image, this is what you'll get:
function Image() {
return document.createElementNS('http://www.w3.org/1999/xhtml', 'img');
}
Chrome merely uses the native DOM methods to create an image element.

Categories