Skip to content

Commit

Permalink
Add dns prefetch functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
DorsetDigital committed Jun 12, 2018
1 parent 303a1f5 commit 0f341ae
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ DorsetDigital\CDNRewrite\CDNMiddleware:
add_debug_headers: true
enable_in_dev: true
subdirectory: ''
add_prefetch: true
```

The options are hopefully fairly self explanatory:
Expand All @@ -45,6 +46,7 @@ The options are hopefully fairly self explanatory:
* `add_debug_headers` - if enabled, adds extra HTML headers to show the various operations being applied (default false)
* `enable_in_dev` - enable the CDN in dev mode (default false)
* `subdirectory` - set this if your site is in a subdirectory (eg. for http://www.example.com/silverstripe - set this to 'silverstripe')
* `add_prefetch` - set this to true if you want the module to automatically add a `<link rel="dns-prefetch">` tag to your html head to improve performance

# Notes

Expand Down
29 changes: 29 additions & 0 deletions src/CDNMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use SilverStripe\Core\Injector\Injectable;
use SilverStripe\Control\Director;
use SilverStripe\Admin\AdminRootController;
use SilverStripe\View\HTML;

class CDNMiddleware implements HTTPMiddleware
{
Expand Down Expand Up @@ -70,6 +71,15 @@ class CDNMiddleware implements HTTPMiddleware
*/
private static $subdirectory = '';

/**
* @config
*
* Add dns-prefetch links to the html head
* @var boolean
*/
private static $add_prefetch = false;


/**
* Process the request
* @param HTTPRequest $request
Expand Down Expand Up @@ -135,6 +145,14 @@ private function updateBody(&$body, &$response)
if ($this->config()->get('add_debug_headers') == true) {
$response->addHeader('X-CDN-Assets', 'Enabled');
}

if ($this->config()->get('add_prefetch') === true) {
$prefetchTag = $this->getPrefetchTag();
$body = str_replace('<head>', "<head>".$prefetchTag, $body);
if ($this->config()->get('add_debug_headers') == true) {
$response->addHeader('X-CDN-Prefetch', 'Enabled');
}
}
}

if ($this->config()->get('rewrite_resources') === true) {
Expand Down Expand Up @@ -169,6 +187,17 @@ private function getSubdirectory()
}
return $subDir;
}

private function getPrefetchTag()
{
$atts = [
'rel' => 'dns-prefetch',
'href' => $this->config()->get('cdn_domain')
];
$pfTag = "\n" . HTML::createTag('link', $atts);

return $pfTag;
}

/**
* Determine whether the website is being viewed from an admin protected area or not
Expand Down

0 comments on commit 0f341ae

Please sign in to comment.