When does a Javascript event loop fire on an HTML page?

I know that the JS function (ie setTimeout (function () {...}, TIME)) places the function that it received as a parameter in the browser event loop, and that this event loop will be processed after all incoming / synchronous JS calls.

But what actually happens when it has the following HTML page structure:

<html> <head> <script> MANY INLINED SCRIPTS </script> <script src="file.js"></script> <script> setTimeout(function(){...}, TIME)</script> . . . 

and the page goes, probably this structure repeats until the value </html> is reached.

When will the event queue be processed in this situation?

edit: I want to create some kind of Lazy Loader for scripts on my page. I rely on content coming from other sources, which should appear only after analyzing the DOM and, hopefully, responsive.

0
javascript html javascript-events unobtrusive-javascript
source share
1 answer

Each inline script is processed immediately upon detection of the closing </script> . Similarly, <script> tags that import scripts from the server as separate files are processed when the files are received, and this process is synchronous - the browser waits for the contents of the script before processing (except to see the relatively new "asynchronous") attribute for <script> and the old defer attribute in IE, which may or may never have worked predictably (thanks @RobG)).

Thus, your inline code with setTimeout() will be launched when the browser sees the full <script> block, and then the passed function will be called after the specified number of milliseconds has elapsed (approximately). You cannot rely too much on the accuracy of timeout processing.

There are other events besides the timeout mechanism: user interactions, ajax, etc. They all go through the same gateway, conceptually; that is, if you plan to start your timeout, but the user presses the button for a few milliseconds in advance, your timer code will wait for the button to complete processing.

+3
source share

All Articles