Is it possible to run JavaScript before any image loads?
Is this default behavior? Dom, script, IMG load?
Is it possible to run JavaScript before any image loads?
Is this default behavior? Dom, script, IMG load?
Just use the ready function of jQuery.
$(document).ready(function(){
// Your code here.
});
Or, for short you can just do
$(function(){
// Your code here.
});
Yes it is by using window.onload like this :
<script>
function init() {
alert("");
}
window.onload = init;
</script>
This is alternative to answer below because it doesn't use jQuery
You might want to consider reading this
You could just put your script tags in the <head></head> and put your code outside of any function. It will be run before (and while) the browser is parsing the page.
Not useful if you need the DOM to be loaded, of course.
Very basic, and bad form, but it is an option. Just a thought.
Javascript runs before images have loaded by default. The window object's load event fires when images have completed loading (for most clients; some versions of Safari have fired load before images complete), but you're in no way obligated to wait for that event to run code.
The jQuery ready event (as seen in another comment) fires when the DOM is assumed to be ready for complete interaction (and in some clients, the DOM is progressively ready for interaction as it is parsed). It's also not necessary, depending on what code you want to run.
If you want to run code that doesn't depend on the document at all, you can run it in any script tag at any time and it will run immediately as soon as the script is downloaded and parsed. If you want to run code that depends on the DOM but not on images (or, necessarily, styles), you will want to look for a cross-browser DOM-load event simulator (similar to this but not necessarily that, there are a lot of implementations out there). If you want to run code when the page has finished loading, you'll want to use the load event (and you'll want to use an abstraction around window.addEventListener() and window.attachEvent(), rather than assigning to window.onload.