| 1 |
<?php |
| 2 |
include('lib/dom-parser.php'); |
| 3 |
|
| 4 |
function flying_scripts_is_keyword_included($content, $keywords) { |
| 5 |
foreach($keywords as $keyword) { |
| 6 |
if (strpos($content, $keyword) !== false) return true; |
| 7 |
} |
| 8 |
return false; |
| 9 |
} |
| 10 |
|
| 11 |
function flying_scripts_rewrite_html($html) { |
| 12 |
try { |
| 13 |
// Detect non-HTML |
| 14 |
if (!isset($html) || trim($html) === '' || strcasecmp(substr($html, 0, 5), '<?xml') === 0 || trim($html)[0] !== "<") { |
| 15 |
return $html; |
| 16 |
} |
| 17 |
|
| 18 |
// Parse HTML |
| 19 |
$newHtml = str_get_html($html); |
| 20 |
|
| 21 |
// Not HTML, return original |
| 22 |
if (!is_object($newHtml)) return $html; |
| 23 |
|
| 24 |
$include_list = get_option('flying_scripts_include_list'); |
| 25 |
|
| 26 |
foreach ($newHtml->find("script[!type],script[type='text/javascript']") as $script) { |
| 27 |
if(flying_scripts_is_keyword_included($script->outertext, $include_list)) { |
| 28 |
$script->setAttribute("type","lazy"); |
| 29 |
if($script->getAttribute("src")) { |
| 30 |
$script->setAttribute("data-src", $script->getAttribute("src")); |
| 31 |
$script->removeAttribute("src"); |
| 32 |
} |
| 33 |
else { |
| 34 |
$script->setAttribute("data-src", "data:text/javascript;base64,".base64_encode($script->innertext)); |
| 35 |
$script->innertext=""; |
| 36 |
} |
| 37 |
} |
| 38 |
} |
| 39 |
|
| 40 |
return $newHtml; |
| 41 |
|
| 42 |
} catch (Exception $e) { |
| 43 |
return $html; |
| 44 |
} |
| 45 |
} |
| 46 |
|
| 47 |
if (!is_admin()) ob_start("flying_scripts_rewrite_html"); |
| 48 |
|