<img src> w/ timeout? - javascript

I have some tracking pixels on our site, that I'd like to protect against them impacting our user experience if their servers are down or slow. What's the easiest way to specify a maximum time the browser should attempt to load a given img - i.e. try for 100ms and then give up? (I'd rather not track a given customer than have a server hang on the third-party server impact our site).

You could insert the <img> with JavaScript and use setTimeout() to remove it after 100ms.
Example with jQuery:
var tracker = $("<img>", { src: trackingUrl }).appendTo(document.body);
setTimeout(function() { tracker.remove(); }, 100);

you should load them when the document is ready.
or at the lastline ( in the html). this way- it wont hurt the user experience.
document ready can be also used with jQuery.
but you can use window.load.
as a rule(not always) - all scripts should be at the end of the page.
if you want to FORCE time out KILL :
create an img tag.
attach the load event to the img (this function will set flag : downloaded=1;)
set the src.
with setTimeout Function your gonna kill the img.
how ?
if after X MS the downloaded ==0 then kill.
so : each load event( from the IMg) is setting a flag ( downloaded=1).
your timeout function dont care about nothing!!! after x MS she going to kill the img - only if the downloaded==0.

You would have to use javascript to do this, there's nothing native to HTML/HTTP that would do this on a page basis. Google around for "HTML IMG timeout".

as img.parentNode.removeChild(img)
Not all img have containers.
var img = new Image()
img.src = '...third-party server...'
setTimeout(function() {
img.removeAttribute('src')
}, 100)

You could call a server process in the IMG tag. Let it worry about timing out the load.

Related

html2canvas works correctly after wrapping it inside a setTimeout callback, why and what's the perfect solution for this?

I am playing with html2canvas and I figured out it's rendering my DOM incorrectly.
I tried to Google but only see some information about putting html2canvas inside a setTimeout callback like this:
var delay = 1000;
$('#image').css('width', 64);
// if I stopped running the following code, the image is correctly rendered.
setTimeout(function(){
html2canvas($("#h2cwrap")[0]).then(function (canvas) {
showImage64(canvas.toDataURL());
});
},delay)
I noticed that even changing the var delay = 1000 setting would lead to different results. For example, if it's set to var delay = 1, then the image would be resized correctly but aligned wrongly. If it's set to var delay = 1000, the image would be resized and aligned both correctly.
How do I make sure html2canvas renders exactly what I see without using such weird hacks?
The setTimeout could be there to wait for the browser to load all resources including your image and styles.
You could alternatively listen for the load event which will fire after all resources are loaded.
window.addEventListener('load', (event) => {
// All resources in document loaded and parsed
console.log('page is fully loaded');
html2canvas($("#h2cwrap")[0]).then(function (canvas) {
showImage64(canvas.toDataURL());
});
});

Google pagespeed- load images without affecting render time

I have a slider and am loading low grade images to facilitate a quick load.
on window ready i am loading the proper sized images
function loadImages(){
var images= document.getElementById('dhadimages').getElementsByClassName("dhadsecondimg");
var index;
for (index = 0; index < images.length; ++index) {
images[index].src= images[index].dataset.img;
}
}
window.onload = function () { loadImages(); }
but pagespeed counts this as part of the render time. For the moment i am loading when the user clicks on something and obviously this works, but why is pagespeed not detecting window.onload and stopping measurements there? Is there any techniques beside delay or any later events to bind to?
Add the async tag to your script (you may have to make this a separate script to enable you to do this). The browser executes all of your JS before "saying" it's finished with the DOM. Adding async as a tag to this script lets the browser continue building the DOM without waiting for the image loads.

How can i Check if <object> failed to load?

I have the following code:
document.getElementById("launcherDiv").innerHTML =
"<object id='launcher'
classid='CLSID:17E88883-3488-46B8-BE4D-30568888855'
codebase='Helper.CAB#version=8,8,8,88'>
</object>";
Let say the download/installing failed,
How can I know this? depending of it that I can't know how much time it supposed to take..
If I will check in a loop how can I know when to end?
previously I used to define the tag inside the HTML and it waiting until the installation finished or failed.
But now I need delay loading of this ActiveX so I can't use this
Can anyone help me?
If object tag is failed to load then it will render inner HTML between tag. For example
<object data="my/file/path.pdf">Object not supported</object>
If object fails then it will show inner text i.e. "Object not supported"
Maybe this helps:
var iv = setInterval(function () {
if (document.all["launcher"].readyState == 4) {
clearInterval(iv)
alert("Object loaded")
}
}, 100);
What it does is set an interval which checks the readystate every 100 seconds and if the object has loaded it alerts.
I know this is a old post but I was trying something like this my self.
In the object tag you can do something else inside it.
For example I was making a music site and If the custom player didnt load I wanted the audio tag to take over.
example:
<object>
<load customplayer> <!--==If this fails do the next line ==-->
<audio>
load song
</audio>
</object>
The only difference between the (first) anchor in an object that successfully loaded embedded content and the fallback content (first) anchor in an object that did not successfully load are the dimensions of the element. So all you have to do is determine your policy of the element you use for fallback (this is very likely an anchor element though some people might still support Flash as fallback content) and then target that element and get it's height in example; if the height is greater than 0 the object element did not successfully load.
var o = document.getElementsByTagName('object');
console.log(o[0].getElementsByTagName('a')[0].getBoundingClientRect().height);

Changing <img src="XXX" />, js event when new image has finished loading?

I have a photo gallery web page where a single <img src="XXX" /> element's src is changed (on a click) with JavaScript to show the next image—a poor man's ajax I guess. Works great on faster connections when the new image appears almost immediately. Even if it takes a few seconds to load, every browser I've tested it on keeps the old image in place until the new one is completely loaded.
It's a little confusing waiting those few seconds on a slow connection, though, and I'm wondering if there's some JavaScript event that fires when the new image is done loading, allowing me to put a little working... animated gif or something up in the meantime.
I know I could use AJAX for real (I'm using jQuery already), but this is such a nice and simple solution. Besides this lag, is there any other reason I should stay away from this approach to changing images?
You can set up a handler on the "load" event.
$('img.whatever')
.load(function() { /* do stuff */ })
.attr('src', newURL);
Actually I guess you'd want to do this with "live()":
$('img.reloadable').live('load', function() { $(this).show(); });
// ...
$('img#someId').hide().attr('src', newURL);
edit — whoa, where did that year go? Well, it turns out that one problem with that "live" approach I typed in way back when is that the "load" event does not bubble. Now what you can do, however, is leverage the way that "Image" objects (as opposed to <img> DOM elements) behave. Basically, the function that changes the URL can use an "Image" element as the place to keep the handler. The code that changes the actual "src" attribute of the real <img> tag would then also update the "src" of the "Image" object instance. The browser will only really load the image once (assuming cache control is all cool), but the browser will still call the "onload" handler of the "Image":
(function() {
var imageObj = new Image();
imageObj.onload = function() {
// code to run when image loads from server
};
$('#hypotheticalButton').click(function() {
$('#imgToUpdate').attr('src', newURL);
imageObj.src = newURL;
});
})();
You just just preload the images with jQuery so that way when the user clicks, the next image is already loaded and there shouldn't be a delay...that is unless the user goes to your page, and starts clicking on the image before they are loaded.
http://engineeredweb.com/blog/09/12/preloading-images-jquery-and-javascript
var slideimg = $('#slideimage');
slideimg.click(function(){
var img = new Image();
var url = 'url_to_next_image.jpg';
$(img).bind('load',function(){
$('#loading').hide();
slideimg.attr('src',url);
}).attr('src',url);
$('#loading').show();
});
This should work even with IE's crazy cache handling.

Having troubles preloading images with javascript

I'm trying to preload about 150 images and I want to be able to be able to do two things...
1) The images are being preloaded using a list of file names. Not every single file name in the list has a file to match up to it.
eg) pic04.jpg may not exist, even if it is in the list.
So when I'm preloading, i would like to be able to figure out whether or not the image exists, if possible.
2) Right now the function is simply preloading all 150 images using
pictures[i] = new Image();
pictures[i].src = "path/to/my/images/" + imageName[i] + ".jpg";
The function executes extremely fast, but the images don't seem to have been preloaded. Do I need to do something to make the site wait til the images have loaded before continuing?
Any ideas?
The function executes extremely fast, but the images don't seem to have been preloaded.
the images are being loaded asynchronously. The function finishes its execution but the browser continues loading the images in background
So when I'm preloading, i would like to be able to figure out whether or not the image exists, if possible.
yes, it is possible. You can use onerror event handler on the Image object
var img = new Image();
img.onerror=function(){alert('error: '+this.src);}
img.onload=function(){alert('image loaded: '+this.src);}
img.src='path/to/image.jpg';

Categories