Experimenting With Link Rel=preconnect Using Custom Script Injection in WebPageTest
The preconnect Resource Hint is a great way to speed up content that comes from third-party origins – it’s got relatively low overhead (though it’s not completely free) and is generally easy to implement.
Browsers typically only make a connection to an origin just before they request a resource from it, so when resources are discovered late such as CSS background images, fonts, or script injected resources, or resources are considered a low priority, as Chrome does with images, the delay in making the connection becomes part of the critical path for that resource.
Preconnect enables us to create the connection in advance – removing it from the critical path for a resource, allowing the resource to be loaded sooner and hopefully improving the overall performance of a page too.
Implementing preconnect is often one of the first improvements I get clients to action but I’ve never been completely happy with my process…
Lighthouse offers some recommendations on which origins to preconnect to, but I tend to use a combination of WebPageTest and DevTools to identify candidates.
I make recommendations to the client I’m working with, their development team implement the preconnect directives and then we typically check the effect in a pre-production environment and adjust as necessary.
If I’m sat with the development team these cycles can be quick, but if the client’s using an external development team, or the team’s offshore they can be long.
What I wanted was a way to experiment, evaluate the options and demonstrate the gains before a client commits my recommendations to code.
Then I remembered WebPageTest has the ability to inject a custom script into the page being tested… I could create a script that adds preconnect directives and see what effect different options have on page speed.
Injecting the Script
At the bottom of the Advanced Tab there’s a text box labelled Inject Script, any script placed in here will be injected into the page shortly after it starts loading.
The script I use to create the <link rel=preconnect elements loops around an array of origins, adds a link element for each to a document fragment, and then adds the fragment to the DOM.