I intend to use JS to inject a prefetch link like this into the document, after page load:
<link rel="prefetch" href="https://www.example.com">
Would this initiate pre-fetching? Or are links with rel= prefetch
and preload
only respected if they were part of the document at time of page load?
Yes, it is supposed to work too. The HTML specs say for <link type=prefetch>
that
The appropriate times to fetch and process this type of link are:
When the external resource link is created on a link element that is already browsing-context connected.
When the external resource link's link element becomes browsing-context connected.
[...]
So when the <link>
element is appended to the document, its fetch and process algorithm is called.
Note that the previous and now deprecated Resource Hints specs where even clearer on that and stated
The resource hint link's may be specified in the document markup, MAY be provided via the HTTP
Link
header, and MAY be dynamically added to and removed from the document.
The last part is the one we're interested in.
It went so far as being one of the use-cases exposed by this very document:
The prefetch can be used to implement a "reactive prefetch strategy" that leverages the knowledge of where the user is heading next and enables the application to begin prefetching critical resources in parallel with the navigation request.
To achieve the above behavior the application can listen for click, or other user and application generated events, and dynamically insert relevant prefetch relations for critical resources required by the next navigation. In turn, the user agent can fetch the hinted resources in parallel with the navigation request, making the critical resources available sooner.