Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parallelize downloads across hostnames on WordPress?

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 ?

like image 728
Leoncio Avatar asked Dec 24 '22 11:12

Leoncio


1 Answers

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);
like image 165
Leoncio Avatar answered Feb 20 '23 10:02

Leoncio