You are here

public function DeferCss::defer in Advanced CSS/JS Aggregation 8.4

Same name and namespace in other branches
  1. 8.3 advagg_mod/src/Asset/DeferCss.php \Drupal\advagg_mod\Asset\DeferCss::defer()

Replace stylesheet links with preload & noscript links.

Parameters

string $content: The response content.

Return value

string Updated content.

File

advagg_mod/src/Asset/DeferCss.php, line 55

Class

DeferCss
Modify stylesheet links to defer them. May lead to Flash of unstyled content.

Namespace

Drupal\advagg_mod\Asset

Code

public function defer($content) {
  if ($this->external) {
    $pattern = '/<link rel=["\']stylesheet["\'](.*)(href="[a-zA-Z0-9\\/_\\.\\-\\?\\:]*")(.*)\\/\\>/';
  }
  else {
    $pattern = '/<link rel=["\']stylesheet["\'](.*)(href="\\/[a-zA-Z0-9][a-zA-Z0-9\\/_\\.\\-\\?]*")(.*)\\/\\>/';
  }
  $content = preg_replace_callback($pattern, [
    $this,
    'callback',
  ], $content);

  // Put JS inline if configured.
  if ($this->deferMethod === 0) {
    $path = drupal_get_path('module', 'advagg_mod') . '/js/loadCSS.js';
    if (!strpos($content, $path)) {
      $path = Crypt::hashBase64($path . $this->counter);
    }
    else {
      $path = str_replace('/', '\\/', $path);
    }
    $path = preg_quote($path, '/');
    $pattern = "/<script src=['\"]\\/(.*{$path}.*)\\?.*['\"]>/";
    $content = preg_replace_callback($pattern, [
      $this,
      'inlineScript',
    ], $content);
  }
  return $content;
}