4

I am a total beginner in Javascript but not in OOP or HTML. I have started the Beginning Javascript book and have run into trouble with the second example. The following code should display p1 in my browser(Chrome) and then and alert box saying "first". However I do not understand why it is happening the other way around --- alert appears before p1.

<html>
<body>

<p>p1</p>
<script type="text/javascript">
alert("first");
</script>

</body>
</html>

EDIT: As an additional solution to problem of manipulating HTML elements with cross-browser compatability, I think jQuery would be an essential next step for web development after learning Javascript.

Vasu Devan
  • 55
  • 6

2 Answers2

0

The html is being rendered but as the alert is not triggered by any javascript event, it fires as soon as the dom is loaded. You do not have any bug and the behavior of your browser is ok.

Christophe Ferreboeuf
  • 1,048
  • 14
  • 26
0

Please go through the link below to understand the load and execution order of the script.

load and execute order of scripts

Community
  • 1
  • 1
Anoop H.N
  • 1,244
  • 1
  • 15
  • 31
  • 1
    Quoting this article: "When a script tag is inserted dynamically, how the execution order behaves will depend upon the browser. You can see how Firefox behaves in this reference article. In a nutshell, the newer versions of Firefox default a dynamically added script tag to async unless the script tag has been set otherwise." Fitting with this if OPs page is opened in firefox the p tag does indeed appear before alert box. – thodic Feb 24 '17 at 10:35
  • thanks. Converting to a async script and external js file solved my problem. But this still will be an issue for mulitple async scripts. Is there any way currently to reliably control execution order of JS scripts cross-browser? The material I am reading on the net seems to indicate there isnt but the book im learning, "Beginning Javascript", provides code for Firefox and IE while I am testing in Chrome. IE is blocking my script though I have enabled scripting but i will try installing Firefox – Vasu Devan Feb 24 '17 at 12:34
  • I have upvoted it but do not have enough rep to change the score. Sorry. – Vasu Devan Feb 24 '17 at 13:22