Why is preconnect resource hint not working?
Asked Answered
R

1

5

I've created a test page at crenshaw.dev/demo/hints.html with browser hints requesting a dns-prefetch and preconnect to mac9416.com.

<!DOCTYPE html>
<html lang="en-US">
    <head>
        <title>Test resource hints</title>
        <link rel="dns-prefetch" href="//mac9416.com">
        <link rel="preconnect" href="https://mac9416.com" crossorigin>
    </head>
    <body>
        Lorem ipsum dolor sit amet,
        <!-- a bunch more to delay page loading -->
        Duis dignissim gravida commodo.

        <script src="https://mac9416.com/blah.js"></script>
    </body>
</html>

But according to WebPageTest, the connection to mac9416.com isn't happening until after index.html is fully loaded.

WebPageTest waterfall chart showing mac9416.com is connected to only after all markup has been downloaded and parsed, instead of immediately after the head element is parsed

Why isn't Chrome connecting to mac9416.com immediately after <head> is parsed?

UPDATE:

Based on the accepted answer and comment, I wrote up an explanation of the fix.

The crossorigin attribute, when used with rel="preconnect", doesn't describe where the target origin is but rather what kind of assets will be downloaded from that origin. If the assets use CORS, crossorigin is needed. If CORS won't be used, crossorigin should be omitted. If both types of assets will be present, two resource hints are necessary.

Rigging answered 4/4, 2019 at 15:46 Comment(1)
Related: webmasters.stackexchange.com/q/89466/10249Pathless
B
11

Just remove the badly named crossorigin parameter and it will work.

<link rel="preconnect" href="https://mac9416.com">

This parameters doesn't tell the browser that the domain is external (it already knows that). It tells the browser to pre-open a special "CORS" connection, which is needed for fonts or XHR requests, but not for scripts, stylesheets or images.

Busby answered 4/4, 2019 at 16:38 Comment(2)
Test checks out. After some reading, I see that omitting crossorigin basically means "don't use CORS". Out of curiosity, how might one get the preconnect to work while using CORS?Rigging
Scripts don’t use CORS. So did a preconnect for a CORS connection and then requested a non-CORS asset type, which uses a separate connection. If it was a font request or a XHR request then it should have used that CORS connection that you preconnected too. See also developer.mozilla.org/en-US/docs/Web/HTTP/…Lanilaniard

© 2022 - 2024 — McMap. All rights reserved.