Onload doesn't fire on "new Image()", when src is ".js" file - javascript

Am i wrong in assuming, that this should work?
var i = new Image();
i.onload = function () {
alert('foo');
};
i.src = 'http://whatever.com/script.js';
This way onload event doesn't fire at all.
if i replace the last line with
i.src = 'http://somethingelse.com/image.png'
then it does. What could be the problem here? Does it only fire on image sources? What are the allowed content types then? Can't find any info on that.

That's because you're getting an error when you try to load a javascript file as an image, and the onerror event probably fires instead.
The onload event only fires when an image was successfully loaded.
I'm guessing you can pass in almost any URL, as long as it's a valid image that can be loaded !

Related

Function firing before images has finished loading

I'm trying to get a pre loader screen to work but am hitting a roadblock.
My goal: To have the loading animation/divs dissapear when the image has finished loading.
I've tried to accomplish this with a simple .ready function and still the function that removes the loading animation fires white the image is still loading and the viewer will see the image load in real time.
$("#defaultImage").ready(function(){
TweenMax.to(["#backgroundLoad","#loadBoxes"],1,{alpha:0,delay:0.75});
console.log('Page has loaded');
});
Is this incorrect? I thought that this will wait for the entire page(images included) to load and then fire the function inside it.
I've tried the below too and it doesn't seem to fire the console.log at all
document.getElementById("defaultImage").onload = function (){
console.log('Page has loaded');
};
Pen in question below. You can see the issue if you view it in debug view and do a hard refresh.
http://codepen.io/mhcreative/pen/GoxLPo?editors=0011
Any help would be much appreciated.
Thanks, All.
Here try this if you still want it natively.
$(document).ready(function(){
var img = new Image(); // Create new img element
img.addEventListener("load", function() {
TweenMax.to(["#backgroundLoad","#loadBoxes"],1,{alpha:0,delay:0.75});
}, false);
img.src = 'src/to/img'; // Set source path
$("#defaultImage").append(img); //append loaded image inside div
});

How do I make .load() wait till everything is fully loaded? [duplicate]

I have a Python script that is doing some manipulation on a JPEG image. I pass some parameters to this script and call it from my HTML page. The script returns an img src="newimage.jpg tag.
I know how to wait for the reply from the script but I don't know how to tell when the image is fully loaded (when it is, I want to display it). What I get now is the image loading slowly so the user is seeing this "loading" process. Instead, I want to have a msg telling the user to wait while the image is loading, only then I want to display the image.
You can dynamically create a new image, bind something to its load event, and set the source:
$('<img>').bind('load', function() {
$(this).appendTo('body');
}).attr('src', image_source);
Image Loading
Wait for ajaxRequest
The other answers have mentioned how to do so with jQuery, but regardless of library that you use, ultimately you will be tying into the load event of the image.
Without a library, you could do something like this:
var el = document.getElementById('ImgLocation');
var img = document.createElement('img');
img.onload = function() {
this.style.display = 'block';
}
img.src = '/path/to/image.jpg';
img.style.display = 'none';
el.appendChild(img);

Gif loader while loading heavy png image

I load png image generated by server-side PHP script (chart) to the HTML IMG-element <img id="chart"> using following JS code:
$('#chart').attr('src', 'chart.php');
The PNG-image generation and downloading takes about 1 second, so I want to show gif loader while image is loading. How to implement this feature with JS?
For balance this is very simple to do in plain JS:
var preload = function(element, src) {
var img = new Image();
// Apply onload before applying src attribute to avoid IE prematurely firing
img.onload = function() {
// Replace #chart with image
element.parentNode.replaceChild(img, element);
};
img.src = src;
}
preload(document.getElementById('chart'), 'chart.php?_...');
$('#chart').attr('src', 'chart.php').load(function(){
//something
});
In case the browser caches it, you may way to add something to the query string to break that. Either way, you need to listen for the image's load event, which should be bound before setting its src (in case it's cached):
var target_url = 'chart.php?_=' + (new Date()).getTime();
// Show "loading"
$('#chart').on("load", function () {
// Hide "loading"
}).attr('src', target_url);
Reference:
http://api.jquery.com/load-event/
Note the caveats near the bottom of that reference, referring to the event when working with images:
It doesn't work consistently nor reliably cross-browser
It doesn't fire correctly in WebKit if the image src is set to the same src as before
It doesn't correctly bubble up the DOM tree
Can cease to fire for images that already live in the browser's cache

Image width traces zero with onload when cached

I'm building a Javascript lightbox and I'm trying to adjust the size once the image has loaded. I'm using the code below, which works fine - it outputs the correct width once loaded.
My problem:
When I refresh, it will load the image instantly from the cache, and it seems to bypass the load. I get an instant zero for the width. Why does this happen?
My code:
var oImage = new Image();
oImage.src = 'http://mydomain.com/image.png';
container.html(oImage);
oImage.onload = function(){
alert(this.width);
}
** Update **
#Alex: This is the code I've tried with your plugin, I assume I'm probably doing something wrong. I'd be eager to get this working because your plugin looks quite good.
container.waitForImages(function() {
var cWidth = $(this).width();
alert("width: "+cWidth); // returns 0 - works first time but not cached
});
// Adding the image to the container for preload
container.html('<img src="mygraphic.png" />');
You need to do a few things...
Check the complete property of the img element.
Attach the load event before setting the src property.
Also, I found creating a new Image and assigning the src there is the best way to determine if the image has loaded or not.
You may want to switch the .html() and the .onload() calls.
If the image is loading from cache, I'm imagining that the .html() call completes before the script has had a chance to attach a function handler to the image's onload event. Therefore, effectively bypassing the load event itself (as the image has already loaded).
If it's still downloading the image (i.e. not cached), there will be more than enough time to call the .onload attach before the image completely finishes rendering.
While you're at it, you may want to do this the jQuery way, just so you're attaching events more similarly to DOM2 than DOM0.
var image = $('<img/>', {
src : 'http://mydomain.com/image.png'
}).load(function () {
alert(this.width);
})
// maybe clear container before if you want
.appendTo(container);
If we're going to have to set the src after the onload, we might as well do this instead:
var image = $('<img/>')
.load(function () {
alert(this.width);
})
.attr('src','http://mydomain.com/image.png')
.appendTo(container)
;
Hopefully that works cleanly.
This answer JavaScript: Know when an image is fully loaded suggests that you should set onload before setting src

Javascript Image Object - Handle onload Event

I'm trying to preload image on click event:
// new image object
var imgObject = new Image();
// assign the path to the image to the src property
imgObject.src = document.URL + 'image/image.jpg';
// check if image has loaded
if (imgObject.complete) {
But the complete call never returns true on the first click - any idea what I'm missing here?
.complete is a property of the image object, not an event that you can attach to. Use the onload event:
var image = new Image();
image.onload = function() {
alert('image loaded');
};
image.src = document.URL + 'image/image.jpg';
Note: Be sure to attach to the onload hander before setting the source attribute.
Note Explanation: Image caching. If the image is cached then the onload event will fire immediately (sometimes before setting the handler)

Categories

Resources