Search code examples
htmlangularasynchronousdeferred

Script with defer prevents loading of Angular App


I have an Angular app which depends on a script on a server, that isn't always stable. So sometimes it takes some time to get loaded. Therefore I added a defer-attribute on it. But the App waits until the download of the deferred script is finished.

Based on my research the Angular App should render before the DOMContentLoaded. I even tried it with a new Angular App with the same result. I deferred the loading of the defer.js by 10 sec. The HTML of the Angular App looks like the following:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Untitled</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

  <script src="http://localhost:8080/defer.js" defer></script>

</head>
<body>
  <app-root></app-root>
</body>
</html>

Here the result in the Browser

The following HTML gets loaded in the Browser. On the Angular Scripts aren't any defer, so they should be executed IMO.

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Untitled</title>
        <base href="/">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="icon" type="image/x-icon" href="favicon.ico">
        <script src="http://localhost:8080/defer.js" defer=""></script>
        <link rel="stylesheet" href="styles.css">
    </head>
    <body>
        <app-root></app-root>
        <script src="runtime.js" type="module"></script>
        <script src="polyfills.js" type="module"></script>
        <script src="styles.js" defer></script>
        <script src="vendor.js" type="module"></script>
        <script src="main.js" type="module"></script>
    </body>
</html>

(I use the Chrome Browser Plugin 'URL Throttler' to emulate it)


Solution

  • I found the answer. Scripts with type="module" are deferred by default. Therefore the browser blocks the execution to it until the previous defer-scripts are executed