Search code examples
javascriptimageexecution

When are JavaScripts executed?


I'm currently asking myself, when javascripts in the header of a page are executed?

After all contents are loaded? During loading images? Before loading the site?

Reason is, I want to implement a barrier to prevent users accessing a site without javascript (it's for internal company use, don't blame me for the requirement) - my idea was to create a div-error-message that is hidden with javascript and a screenshot of my page greyed out, also hidden if javascript is disabled.

Problem is, such a screenshot can be quite large in terms of file-sizes. So, with a slow connection, would you have to load the whole image before javascript hides it?!


Solution

  • <script> tags in the <head> of an HTML page are executed as they are loaded (unless they have the defer attribute set), that is, before the images, or even the rest of the document have been loaded. What you might want to do is contain the image you wish to hide in a <div id="something" style="display:none"> and show this div after the page and all of its content (your screenshot image included) has loaded (ie. in an onload handler -- or obviously you can use addEventListener too).

    HTH!