When are JavaScripts executed?
-
10-07-2019 - |
Question
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!
OTHER TIPS
Why not just put the "you must have javascript" warning inside a <noscript>
tag?
Javascript in a script
tag executes whenever the browser sees it. But is stops all other execution and (probably) downloading. So, you are trying to hide an img
in the body
, but because the script
tag is in head
it will execute before the img
has loaded so it won't be able to find it (document.getElementById('#noScriptImage')
will fail).
Another option is to place the script
tag after the img
, but then there is a change that for a fraction of a second the image will be visible and the screen will flick.
Javascript will depend on what event are you using; if you're talking about a onload event, so it'll run just after all content loads.
To handle your problem, you could to create a page and, there, to write some javascript to redirect it to JavascriptEnabled.html; if you can't redirect it, you should also to add a META REFRESH tag and redirect it to JavascriptDisabled.html and to display a warning message.