| 1 |
<?php |
| 2 |
include('lib/dom-parser.php'); |
| 3 |
|
| 4 |
function flying_scripts_is_keyword_included($content, $keywords) |
| 5 |
{ |
| 6 |
foreach ($keywords as $keyword) { |
| 7 |
if (strpos($content, $keyword) !== false) { |
| 8 |
return true; |
| 9 |
} |
| 10 |
} |
| 11 |
return false; |
| 12 |
} |
| 13 |
|
| 14 |
function flying_scripts_rewrite_html($html) |
| 15 |
{ |
| 16 |
try { |
| 17 |
// Process only GET requests |
| 18 |
if ($_SERVER['REQUEST_METHOD'] !== 'GET') { |
| 19 |
return $html; |
| 20 |
} |
| 21 |
|
| 22 |
// Detect non-HTML |
| 23 |
if (!isset($html) || trim($html) === '' || strcasecmp(substr($html, 0, 5), '<?xml') === 0 || trim($html)[0] !== "<") { |
| 24 |
return $html; |
| 25 |
} |
| 26 |
|
| 27 |
// Exclude on pages |
| 28 |
$disabled_pages = get_option('flying_scripts_disabled_pages'); |
| 29 |
$current_url = home_url($_SERVER['REQUEST_URI']); |
| 30 |
if (flying_scripts_is_keyword_included($current_url, $disabled_pages)) { |
| 31 |
return $html; |
| 32 |
} |
| 33 |
|
| 34 |
|
| 35 |
// Parse HTML |
| 36 |
$newHtml = str_get_html($html); |
| 37 |
|
| 38 |
// Not HTML, return original |
| 39 |
if (!is_object($newHtml)) { |
| 40 |
return $html; |
| 41 |
} |
| 42 |
|
| 43 |
$include_list = get_option('flying_scripts_include_list'); |
| 44 |
|
| 45 |
foreach ($newHtml->find("script[!type],script[type='text/javascript']") as $script) { |
| 46 |
if (flying_scripts_is_keyword_included($script->outertext, $include_list)) { |
| 47 |
$script->setAttribute("data-type", "lazy"); |
| 48 |
if ($script->getAttribute("src")) { |
| 49 |
$script->setAttribute("data-src", $script->getAttribute("src")); |
| 50 |
$script->removeAttribute("src"); |
| 51 |
} else { |
| 52 |
$script->setAttribute("data-src", "data:text/javascript;base64,".base64_encode($script->innertext)); |
| 53 |
$script->innertext=""; |
| 54 |
} |
| 55 |
} |
| 56 |
} |
| 57 |
|
| 58 |
return $newHtml; |
| 59 |
} catch (Exception $e) { |
| 60 |
return $html; |
| 61 |
} |
| 62 |
} |
| 63 |
|
| 64 |
if (!is_admin()) { |
| 65 |
ob_start("flying_scripts_rewrite_html"); |
| 66 |
} |
| 67 |
|
| 68 |
// W3TC HTML rewrite |
| 69 |
add_filter('w3tc_process_content', function ($buffer) { |
| 70 |
if ( is_admin() ) return $buffer; |
| 71 |
return flying_scripts_rewrite_html($buffer); |
| 72 |
}); |
| 73 |
|