Skip to content

Instantly share code, notes, and snippets.

@cliffordp
Created September 23, 2019 00:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cliffordp/629735962aebec0afd16feebaaef8da0 to your computer and use it in GitHub Desktop.
Save cliffordp/629735962aebec0afd16feebaaef8da0 to your computer and use it in GitHub Desktop.
Add JSDelivr as a prefetch resource provider to speed up page load times in WordPress
<?php
add_filter( 'wp_resource_hints', 'your_add_resource_hints', 10, 2 );
/**
* Try to improve performance with resource hints.
*
* WP will output protocol-relative 'dns-prefetch' for all scripts and styles which are enqueued
* from external hosts.
* WP will not do 'preconnect', 'prefetch', or 'prerender' automatically.
*
* @link https://make.wordpress.org/core/2016/07/06/resource-hints-in-4-6/
* @link https://www.keycdn.com/blog/resource-hints/
* @link https://www.machmetrics.com/speed-blog/guide-to-browser-hints-preload-preconnect-prefetch/
* @link https://caniuse.com/#search=preconnect
* @link https://www.igvita.com/2015/08/17/eliminating-roundtrips-with-preconnect/
* @link https://core.trac.wordpress.org/ticket/38121
* @link https://w3c.github.io/resource-hints/#dfn-preconnect
* @link https://developer.mozilla.org/en-US/docs/Web/HTML/Preloading_content#Cross-origin_fetches
* @link https://html.spec.whatwg.org/multipage/urls-and-fetching.html#cors-settings-attributes
* @link https://wordpress.org/plugins/pre-party-browser-hints/
*
* @param $hints
* @param $relation_type
*
* @return array
*/
function your_add_resource_hints( $hints, $relation_type ) {
if ( 'preconnect' === $relation_type ) {
$hints[] = [
'href' => 'https://cdn.jsdelivr.net/',
'crossorigin' => 'anonymous',
];
}
return $hints;
}
@melroy89
Copy link

melroy89 commented May 8, 2022

I don't know if crossorigin is actually helping you. Unless you are loading fonts inside the css.

@cliffordp
Copy link
Author

Will need to make the choice for each implementation example, but here's an example from https://getbootstrap.com/

<!-- CSS only -->
<link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
crossorigin="anonymous">

@melroy89
Copy link

melroy89 commented May 9, 2022

Ah yes. But with a preconnect link it's another story. Sorry my bad.

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

This is another type of crossorigin attribute.

@cliffordp
Copy link
Author

No sweat, thanks for contributing :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment