protected function afterRequest(HTTPRequest $request, HTTPResponse $response)
    {
        $debugbar = DebugBar::getDebugBar();
        if (!$debugbar) {
            return;
        }
        DebugBar::setRequest($request);

        // All queries have been displayed
        if (DebugBar::getShowQueries()) {
            exit();
        }

        $script = DebugBar::renderDebugBar();

        // If the bar is not renderable, return early
        if (!$script) {
            return;
        }

        // Inject init script into the HTML response
        $body = $response->getBody();
        if (strpos($body, '</body>') !== false) {
            if (Requirements::get_write_js_to_body()) {
                $body = str_replace('</body>', $script . '</body>', $body);
            } else {
                // Ensure every js script is properly loaded before firing custom script
                $script = strip_tags($script);
                $script = "window.addEventListener('DOMContentLoaded', function() { $script });";
                $script = '<script type="application/javascript">//<![CDATA[' . "\n" . $script . "\n</script>";
                $body = str_replace('</head>', $script . '</head>', $body);
            }
            $response->setBody($body);
        }

        // Ajax support
        if (Director::is_ajax() && !headers_sent()) {
            if (DebugBar::isAdminUrl() && !DebugBar::config()->get('enabled_in_admin')) {
                return;
            }
            // Skip anything that is not a GET request
            if (!$request->isGET()) {
                return;
            }
            // Always enable in admin because everything is mostly loaded through ajax
            if (DebugBar::config()->get('ajax') || DebugBar::isAdminUrl()) {
                $headers = $debugbar->getDataAsHeaders();

                // Prevent throwing js errors in case header size is too large
                if (is_array($headers)) {
                    $maxHeaderLength = DebugBar::config()->get('max_header_length');
                    $debugbar->sendDataInHeaders(null, 'phpdebugbar', $maxHeaderLength);
                }
            }
        }
    }