Does inline javascript block the UI thread?

后端 未结 3 1753
感情败类
感情败类 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

提交回复
热议问题