Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to run JavaScript before any image loads?

Tags:

javascript

Is it possible to run JavaScript before any image loads?

Is this default behavior? Dom, script, IMG load?

like image 783
Matrym Avatar asked Apr 24 '10 06:04

Matrym


1 Answers

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.
like image 105
eyelidlessness Avatar answered Sep 16 '22 18:09

eyelidlessness