I know PHP, server-side scripts, run first and output the html to the browser, then javascript is executed. However, I am trying to get a feel for how the javascript is executed and can't quite figure it out.
Is Javascript executed top-down and is consistent with this top-down execution? I am dynamically creating javascript in PHP which is triggered by events in my webpage's original javascript.
Will created JS execute exactly where I put it or will it fire before? after?
Thanks
4 Answers 4
Well javascript will execute one line after the another. But also javascript is the event based language hence there will be certain part of the code which will be based on events and will execute only when the events take place.
For eg: click,hover etc events
or functions like setTimeout and setInterval
these function will execute only when the particular events takes place
Comments
JavaScript is executed by the clients browser and is parsed in conjunction with the HTML and CSS, whichever comes first.
Is Javascript executed top-down and is consistent with this top-down execution?
Yes
Will created JS execute exactly where I put it or will it fire before? after?
JavaScript inserted into the DOM will be parsed/executed immediately.
3 Comments
JavaScript, makes an asynchronous call to a server resource (foo.com\some\resource). when the response returns the client code will execute a callback function — this is where the DOM should be updated with the response from the server ...DOM a <script> that performs an AJAX call it will execute immediately ...Javascript is read and run by the user's web browser whereas PHP is run server-side. The PHP code is compiled, HTML (with Javascript) is served, the user's browser reads the HTML and Javascript.
Comments
Is Javascript executed top-down and is consistent with this top-down execution?
Yes
With a lesser-known exception:
Function statements will be executed before any other statements (but not function operators).
So this would run fine:
f();
function f() { console.log("a"); }