How to parallelize downloads across hostnames on WordPress?

Leoncio picture Leoncio · Dec 21, 2015 · Viewed 11.2k times · Source

I'm getting this message "Parallelize downloads across hostnames" when checking my WordPress site on GTmetrix > https://gtmetrix.com

Here are the details > https://gtmetrix.com/parallelize-downloads-across-hostnames.html

How do I fix that ?

Answer

Leoncio picture Leoncio · Dec 21, 2015

Details

Web browsers put a limit on the number of concurrent connections they will make to a host. When there are many resources that need to be downloaded, a backlog of resources waiting to be downloaded will form. The browser will make up as many simultaneous connections to the server as the browser allows in order to download these resources, but then will queue the rest and wait for the requests to finish.

The time spent waiting for a connection to finish is referred to as blocking and reducing this blocking time can result in a faster loading page. The waterfall diagram below shows a page which loads 45 resources from the same host. Notice how long the resources are blocked (the brown segments), before they are downloaded (the purple segments) as they wait for a free connection.


So here is a hack to implement it on WordPress.

In order to work properly, all subdomains/hostnames MUST have the same structure/path. Ex:

  • example.com/wp-content/uploads/2015/11/myimage.jpg
  • media1.example.com/wp-content/uploads/2015/11/myimage.jpg
  • media2.example.com/wp-content/uploads/2015/11/myimage.jpg

Add to functions.php

function parallelize_hostnames($url, $id) {
 $hostname = par_get_hostname($url);
 $url =  str_replace(parse_url(get_bloginfo('url'), PHP_URL_HOST), $hostname, $url);
 return $url;
}

function par_get_hostname($name) {
 //add your subdomains below, as many as you want.
 $subdomains = array('media1.mydomain.com','media2.mydomain.com');
 $host = abs(crc32(basename($name)) % count($subdomains));
 $hostname = $subdomains[$host];
 return $hostname;
}
add_filter('wp_get_attachment_url', 'parallelize_hostnames', 10, 2);