Does inline javascript block the UI thread?

后端 未结 3 1752
感情败类
感情败类 2021-01-22 13:38

I read this nice article on how external scripts block the UI thread but it wasn\'t clear to me whether the blocking is actually due to the presence of the

相关标签:
3条回答
  • 2021-01-22 14:07

    Outside of web workers, which are their own beast, consider the HTML web page and associated Javascript as single threaded.[1]

    Thus, if any javascript is running on the page, then the entire user interface is blocked. Things like window.alert(), window.confirm() and window.prompt() block the entire UI until they are cleared, but even an infinite loop will freeze the browser window[2] until it has finished.

    EDIT -- based on comments and edit to the question:

    The link provided in the original question doesn't refer to the execution of Javscript running, but the sync vs async nature of Javscript loading. I'll give you one example of why such blocking may occure.

    In the way-back days of Javscript, the function document.write() was the only way to have Javascript interact with the web page. As such, when the web page came across a request for a Javascript file to load, the browser had to put everything else on hold -- just in case the Javascript file used document.write to inject something into the stream.

    In today's world, this doesn't happen as much and so browsers give the page designer a way to say 'I promise this Javascript file doesn't care exactly when it is loaded and it won't use document.write() or anything else tricky. You don't have to freeze until it is done.

    This is why modern web browsers have a defer and async attributes.

    1. Opera is special, but we'll ignore that.
    2. Or entire browser, depending
    0 讨论(0)
  • 2021-01-22 14:10

    alert() or any other prompting actions will block the thread until the user responds to the prompt. No matter where they are...

    Update ( regarding the comment ) :

    A browser window parses the HTML and runs the JS with a single thread.. so anything in the javascript code that will take time to complete will block the thread.. no matter what it is.. It can be an alert or an AJAX Request or anything else..

    0 讨论(0)
  • 2021-01-22 14:21

    Any loading of a JS file or any execution of any JS (whether in an external file or inline) will block the UI thread.

    The exception for the <script> tag is an asynchronous load where the script will load and execute asynchronously in the background.

    There are also "deferred" loads (i.e. the defer attribute) which tells the browser not to actually execute the JS therein until the rest of the page has loaded.

    0 讨论(0)
提交回复
热议问题