Which is better <link rel="prefetch" vs script defer?

Viewed 738

I've been using defer attribute with script tags but just found out about the <link rel="prefetch" as="script" is a thing but can not find which is better or preferred? And what is the difference between these methods?

<link rel="prefetch" href="library.js" as="script">

vs

<script defer="" src="library.js"></script>
2 Answers

They're two very different things. <link rel="prefetch"> indicates to the browser that some resource (not necessarily JavaScript) is going to be needed. This is useful if you're loading resources dynamically via JavaScript.

<script defer> alters when the JavaScript code is executed. It is fetched as soon as the browser encounters the element, but it is only run when the document is fully loaded.

They can be similar in these cases:

  • <link rel="prefetch"> in the <head> and <script> in the end of the <body>
  • <script defer> in the <head>

In both cases, the JavaScript resource is fetched at the same time but in the first example, the JavaScript is executed just before the whole <body> is loaded, while in the second, the JavaScript is executed after the whole document is loaded (i.e. all the elements are in the DOM).


About which is better: I would use <script defer> in the <head> instead because:

  • It doesn't block the HTML parser,
  • It has better compatibility and
  • Less stuff to write.

defer on a script will load and execute the script.

A link with prefetch will instruct the browser to load a resource with low priority, but it won’t do anything else with it except caching.

So if you you want to load and execute a script you need to use a script tag. If you want that the browser loads a script because it might be needed in the near future but you don’t want to execute it yet you use prefetch

Related