/
wp-lozad-lazyload.php
381 lines (332 loc) · 11 KB
/
wp-lozad-lazyload.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
<?php
/*
* Plugin Name: WP Lozad Lazy Load
* Description: Lazy Load images, iframes, scripts, and other content with the Lozad library
* Version: 0.0.4
* Author: Jonathan Stegall
* License: GPL-2.0+
* Text Domain: wp-lozad-lazyload
*/
class WP_Lozad_LazyLoad {
/**
* @var string
* Prefix for plugin options
*/
private $option_prefix;
/**
* @var string
* Current version of the plugin
*/
private $version;
/**
* @var string
* The plugin's slug so we can include it when necessary
*/
private $slug;
/**
* @var object
*/
private $admin;
/**
* @var object
* Static property to hold an instance of the class; this seems to make it reusable
*
*/
static $instance = null;
/**
* Load the static $instance property that holds the instance of the class.
* This instance makes the class reusable by other plugins
*
* @return object
*
*/
static public function get_instance() {
if ( null === self::$instance ) {
self::$instance = new WP_Lozad_LazyLoad();
}
return self::$instance;
}
/**
* This is our constructor
*
* @return void
*/
public function __construct() {
$this->option_prefix = 'wp_lozad_lazyload_';
$this->version = '0.0.4';
$this->slug = 'wp-lozad-lazyload';
// do we want to lazy load any thing or turn it off?
$this->lazy_load_anything = filter_var( get_option( $this->option_prefix . 'lazy_load_anything', false ), FILTER_VALIDATE_BOOLEAN );
// do we want to filter post_content to lazy load things inside it?
$this->lazy_load_post_content = filter_var( get_option( $this->option_prefix . 'lazy_load_post_content', false ), FILTER_VALIDATE_BOOLEAN );
// do we want to filter images?
$this->lazy_load_images = filter_var( get_option( $this->option_prefix . 'lazy_load_images', false ), FILTER_VALIDATE_BOOLEAN );
// do we want to filter iframes?
$this->lazy_load_iframes = filter_var( get_option( $this->option_prefix . 'lazy_load_iframes', false ), FILTER_VALIDATE_BOOLEAN );
// load admin
$this->admin = $this->load_admin();
$this->add_actions();
}
/**
* load the admin stuff
* creates admin menu to save the config options
*
* @return object
* Instance of User_Account_Management_Admin
*/
private function load_admin() {
require_once( plugin_dir_path( __FILE__ ) . 'classes/class-' . $this->slug . '-admin.php' );
$admin = new WP_Lozad_LazyLoad_Admin( $this->option_prefix, $this->version, $this->slug );
add_filter( 'plugin_action_links', array( $this, 'plugin_action_links' ), 10, 2 );
add_action( 'plugins_loaded', array( $this, 'textdomain' ) );
return $admin;
}
/**
* Display a Settings link on the main Plugins page
*
* @param array $links
* @param string $file
* @return array $links
* These are the links that go with this plugin's entry
*/
public function plugin_action_links( $links, $file ) {
if ( plugin_basename( __FILE__ ) === $file ) {
$settings = '<a href="' . get_admin_url() . 'options-general.php?page=' . $this->slug . '">' . __( 'Settings', 'wp-lozad-lazyload' ) . '</a>';
array_unshift( $links, $settings );
}
return $links;
}
/**
* Load textdomain
*
* @return void
*/
public function textdomain() {
load_plugin_textdomain( 'wp-lozad-lazyload', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
}
/**
* Add plugin shortcodes, actions, and filters
*
* @return void
*/
private function add_actions() {
add_action( 'init', array( $this, 'init' ) );
}
/**
* Initialize plugin
*
* @return void
*/
public function init() {
// filter to deal with supplied html
if ( true === $this->lazy_load_anything ) {
add_filter( $this->option_prefix . 'convert_html', array( $this, 'convert_html' ), 10, 2 );
}
// add css and javascript
add_action( 'wp_enqueue_scripts', array( $this, 'add_scripts_and_styles' ) );
// don't do any lazy loading of post_content if we're inside the admin
if ( is_admin() ) {
return;
}
// deal with things inside post_content
add_filter( 'the_content', array( $this, 'edit_post_content' ), 1000, 1 );
}
/**
* Process items in post_content
*
* @param string $content
* @return string $content
*/
public function edit_post_content( $content ) {
// if the option is not true, get out
if ( true !== $this->lazy_load_post_content ) {
return $content;
}
// if this is not a singular item, get out
if ( ! is_singular() ) {
return $content;
}
// if this is not the main query, get out
if ( ! is_main_query() ) {
return $content;
}
// if this is a feed, get out
if ( is_feed() ) {
return $content;
}
// Don't reprocess the content
if ( false !== strpos( $content, 'lazy-load' ) ) {
return $content;
}
$current_object = get_queried_object();
if ( is_object( $current_object ) ) {
$post_type = isset( $current_object->post_type ) ? $current_object->post_type : '';
}
// Don't parse post_content if this post is not a supported type
$post_types = get_option( $this->option_prefix . 'post_types', array() );
if ( ! in_array( $post_type, $post_types ) ) {
return $content;
}
try {
$dom = new DOMDocument( null, 'UTF-8' );
// @codingStandardsIgnoreStart
@$dom->loadHTML( mb_convert_encoding( $content, 'HTML-ENTITIES', 'UTF-8' ) );
// @codingStandardsIgnoreEnd
$content = $this->process_images( $dom ); // use domdocument to convert images
$content = $this->process_iframes( $content ); // use content string to convert iframes
return $content;
} catch ( Exception $e ) {
return $content;
}
}
/**
* Convert lazy loaded items, if applicable, for lozad libray
*
* @param string|array $output_html
* @param array $params
* @return string|array $output_html
*/
public function convert_html( $output_html, $params = array() ) {
if ( false === $this->lazy_load_anything ) {
return $output_html;
}
switch ( $params['html_tag'] ) {
case 'script':
// todo: need to document how this works because it's very specific
// this also requires postscribe to be enabled via plugin settings
$output_html['script'] = '<div class="lozad" data-src="' . $params['url'] . '"></div>';
break;
case 'img':
case 'image':
if ( false === $this->lazy_load_images ) {
return $output_html;
}
$dom = new DOMDocument();
// @codingStandardsIgnoreStart
@$dom->loadHTML( $output_html );
// @codingStandardsIgnoreEnd
$output_html = $this->process_images( $dom );
break;
case 'iframe':
if ( false === $this->lazy_load_iframes ) {
return $output_html;
}
// todo: this is rather generic, but should still document it
$output_html = $this->process_iframes( $output_html );
break;
default:
// if the filter doesn't have a way to catch the given markup, it doesn't do anything.
$output_html = $output_html;
break;
}
return $output_html;
}
/**
* Process image tags for lazod
*
* @param string $dom
* @return string $output_html
*/
private function process_images( $dom ) {
$images = [];
foreach ( $dom->getElementsByTagName( 'img' ) as $node ) {
$images[] = $node;
}
foreach ( $images as $node ) {
// if this image has a no-lazy class, get out
if ( $node->hasAttribute( 'class' ) && strstr( $node->getAttribute( 'class' ), 'no-lazy' ) ) {
continue;
}
// create the content for noscript
$fallback = $node->cloneNode( true );
// change src to data-src
$oldsrc = $node->getAttribute( 'src' );
$node->setAttribute( 'data-src', $oldsrc );
$node->removeAttribute( 'src' );
// change srcset to data-srcset
$oldsrcset = $node->getAttribute( 'srcset' );
$node->setAttribute( 'data-srcset', $oldsrcset );
$node->removeAttribute( 'srcset' );
// placeholder image for src
$placeholder_src = get_option( $this->option_prefix . 'placeholder_image_src', '' );
$placeholder_src = apply_filters(
$this->option_prefix . 'placeholder_image_src',
'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
);
if ( '' !== $placeholder_src ) {
$node->setAttribute( 'src', $placeholder_src );
}
// preserve existing classes, if applicable, and add lazy-load as a class
$classes = $node->getAttribute( 'class' );
if ( ! empty( $classes ) ) {
$newclasses = $classes . ' lazy-load';
} else {
$newclasses = 'lazy-load';
}
$node->setAttribute( 'class', $newclasses );
// populate the noscript element
$noscript = $dom->createElement( 'noscript', '' );
// @codingStandardsIgnoreStart
$node->parentNode->insertBefore( $noscript, $node );
// @codingStandardsIgnoreEnd
$noscript->appendChild( $fallback );
}
// save the html
$output_html = preg_replace( '/^<!DOCTYPE.+?>/', '', str_replace( array( '<html>', '</html>', '<body>', '</body>' ), array( '', '', '', '' ), $dom->saveHTML() ) );
return $output_html;
}
/**
* Process iframe tags for lazod
*
* @param string $output_html
* @return string $output_html
*/
private function process_iframes( $output_html ) {
$output_html = preg_replace( '/<iframe(.*?)(src=)(.*?)>/i', '<iframe$1data-$2$3>', $output_html );
return $output_html;
}
/**
* Enqueue CSS and JavaScript libraries for front end
*
*/
public function add_scripts_and_styles() {
if ( true === $this->lazy_load_anything ) {
// allow individual posts to disable lazyload. this can be useful in the case of unresolvable javascript conflicts.
if ( is_singular() ) {
global $post;
if ( get_post_meta( $post->ID, $this->option_prefix . 'prevent_lozad_lazyload', true ) ) {
return;
}
}
wp_enqueue_style( $this->slug, plugins_url( 'assets/css/' . $this->slug . '.min.css', __FILE__ ), array(), $this->version, 'all' );
$lozad_dependencies = array();
// if javascript call lazy loading is allowed, we need postscribe library
if ( true === filter_var( get_option( $this->option_prefix . 'allow_lazy_load_javascript', false ), FILTER_VALIDATE_BOOLEAN ) ) {
$lozad_dependencies[] = 'postscribe';
wp_enqueue_script( 'postscribe', 'https://cdnjs.cloudflare.com/ajax/libs/postscribe/2.0.8/postscribe.min.js', array(), '2.0.8', true );
}
if ( true === filter_var( get_option( $this->option_prefix . 'use_intersectionobserver_polyfill', false ), FILTER_VALIDATE_BOOLEAN ) ) {
wp_enqueue_script( 'intersectionobserverpolyfill', plugins_url( 'assets/js/intersectionobserver.min.js', __FILE__ ), array(), filemtime( plugin_dir_path( __FILE__ ) . 'assets/js/intersectionobserver.min.js' ), true );
$lozad_dependencies[] = 'intersectionobserverpolyfill';
}
wp_enqueue_script( 'lozad', 'https://cdn.jsdelivr.net/npm/lozad/dist/lozad.min.js', $lozad_dependencies, '1.6.0', true );
wp_add_inline_script(
'lozad',
"
if (typeof lozad != 'undefined') {
window.addEventListener('load', function() {
window.lozad('.lazy-load', {
rootMargin: '300px 0px',
loaded: function (el) {
el.classList.add('is-loaded');
}
}).observe();
});
}
"
);
}
}
}
// Initialize the plugin
$wp_lozad_lazyload = WP_Lozad_LazyLoad::get_instance();