PluginProbe
Flying Scripts: Delay JavaScript to Improve Site Speed & Performance / 1.1.9
Flying Scripts: Delay JavaScript to Improve Site Speed & Performance v1.1.9
trunk 1.0.0 1.1.0 1.1.1 1.1.2 1.1.3 1.1.4 1.1.5 1.1.6 1.1.7 1.1.8 1.1.9 1.2.0 1.2.1 1.2.2 1.2.3 1.2.4
flying-scripts / html-rewrite.php

html-rewrite.php in Flying Scripts: Delay JavaScript to Improve Site Speed & Performance 1.1.9, at html-rewrite.php

60 lines 1.8 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
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 // Detect non-HTML
18 if (!isset($html) || trim($html) === '' || strcasecmp(substr($html, 0, 5), '<?xml') === 0 || trim($html)[0] !== "<") {
19 return $html;
20 }
21
22 // Parse HTML
23 $newHtml = str_get_html($html);
24
25 // Not HTML, return original
26 if (!is_object($newHtml)) {
27 return $html;
28 }
29
30 $include_list = get_option('flying_scripts_include_list');
31
32 foreach ($newHtml->find("script[!type],script[type='text/javascript']") as $script) {
33 if (flying_scripts_is_keyword_included($script->outertext, $include_list)) {
34 $script->setAttribute("data-type", "lazy");
35 if ($script->getAttribute("src")) {
36 $script->setAttribute("data-src", $script->getAttribute("src"));
37 $script->removeAttribute("src");
38 } else {
39 $script->setAttribute("data-src", "data:text/javascript;base64,".base64_encode($script->innertext));
40 $script->innertext="";
41 }
42 }
43 }
44
45 return $newHtml;
46 } catch (Exception $e) {
47 return $html;
48 }
49 }
50
51 if (!is_admin()) {
52 ob_start("flying_scripts_rewrite_html");
53 }
54
55 // W3TC HTML rewrite
56 add_filter('w3tc_process_content', function ($buffer) {
57 if ( is_admin() ) return $buffer;
58 return flying_scripts_rewrite_html($buffer);
59 });
60