Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between `script` and `link as="script"` tags

Additionally to the standard method of loading scripts:

<script src="js/script.js"></script>

I have seen people do this:

<link href="js/script.js" as="script"> 

Is there any difference?


Note: There's a similar What's the difference between using link and script tag to reference JavaScript source? question asking about <link href="script.js" type="text/javascript" />, which is different.

like image 699
leonheess Avatar asked Jun 29 '18 16:06

leonheess


1 Answers

If that link tag had rel="preload" (or rel="modulepreload") on it, it would indicate a preload request, which would preload, but not run, the script. In contrast, script loads and runs the script. But without rel, that link is invalid and has no useful effect (at least in terms of the specification).

If you look up link in the spec, you'll see as listed as:

as — Potential destination for a preload request (for rel="preload" and rel="modulepreload")

Following the link to as attribute, it says:

The as attribute specifies the potential destination for a preload request for the resource given by the href attribute. It is an enumerated attribute. Each potential destination is a keyword for this attribute, mapping to a state of the same name. The attribute must be specified on link elements that have a rel attribute that contains the preload keyword. It may be specified on link elements that have a rel attribute that contains the modulepreload keyword; in such cases it must have a value which is a script-like destination. For other link elements, it must not be specified.

like image 194
T.J. Crowder Avatar answered Oct 13 '22 11:10

T.J. Crowder