1

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

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

oh ok, so if I dynamically create a script (say a function call) with ajax and PHP, it will execute right away. so I will not have to reload the page first?
the client code, 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 ...
@MattHintzke yes, if you create and insert into the DOM a <script> that performs an AJAX call it will execute immediately ...
0

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

0

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"); }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.