lazy-images.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. <?php
  2. class Jetpack_Lazy_Images {
  3. private static $__instance = null;
  4. /**
  5. * Singleton implementation
  6. *
  7. * @return object
  8. */
  9. public static function instance() {
  10. if ( is_null( self::$__instance ) ) {
  11. self::$__instance = new Jetpack_Lazy_Images();
  12. }
  13. return self::$__instance;
  14. }
  15. /**
  16. * Registers actions
  17. */
  18. private function __construct() {
  19. if ( is_admin() ) {
  20. return;
  21. }
  22. /**
  23. * Whether the lazy-images module should load.
  24. *
  25. * This filter is not prefixed with jetpack_ to provide a smoother migration
  26. * process from the WordPress Lazy Load plugin.
  27. *
  28. * @module lazy-images
  29. *
  30. * @since 5.6.0
  31. *
  32. * @param bool true Whether lazy image loading should occur.
  33. */
  34. if ( ! apply_filters( 'lazyload_is_enabled', true ) ) {
  35. return;
  36. }
  37. add_action( 'wp_head', array( $this, 'setup_filters' ), 9999 ); // we don't really want to modify anything in <head> since it's mostly all metadata
  38. add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_assets' ) );
  39. // Do not lazy load avatar in admin bar
  40. add_action( 'admin_bar_menu', array( $this, 'remove_filters' ), 0 );
  41. add_filter( 'wp_kses_allowed_html', array( $this, 'allow_lazy_attributes' ) );
  42. add_action( 'wp_head', array( $this, 'add_nojs_fallback' ) );
  43. }
  44. public function setup_filters() {
  45. add_filter( 'the_content', array( $this, 'add_image_placeholders' ), PHP_INT_MAX ); // run this later, so other content filters have run, including image_add_wh on WP.com
  46. add_filter( 'post_thumbnail_html', array( $this, 'add_image_placeholders' ), PHP_INT_MAX );
  47. add_filter( 'get_avatar', array( $this, 'add_image_placeholders' ), PHP_INT_MAX );
  48. add_filter( 'widget_text', array( $this, 'add_image_placeholders' ), PHP_INT_MAX );
  49. add_filter( 'get_image_tag', array( $this, 'add_image_placeholders' ), PHP_INT_MAX);
  50. add_filter( 'wp_get_attachment_image_attributes', array( __CLASS__, 'process_image_attributes' ), PHP_INT_MAX );
  51. }
  52. public function remove_filters() {
  53. remove_filter( 'the_content', array( $this, 'add_image_placeholders' ), PHP_INT_MAX );
  54. remove_filter( 'post_thumbnail_html', array( $this, 'add_image_placeholders' ), PHP_INT_MAX );
  55. remove_filter( 'get_avatar', array( $this, 'add_image_placeholders' ), PHP_INT_MAX );
  56. remove_filter( 'widget_text', array( $this, 'add_image_placeholders' ), PHP_INT_MAX );
  57. remove_filter( 'get_image_tag', array( $this, 'add_image_placeholders' ), PHP_INT_MAX);
  58. remove_filter( 'wp_get_attachment_image_attributes', array( __CLASS__, 'process_image_attributes' ), PHP_INT_MAX );
  59. }
  60. /**
  61. * Ensure that our lazy image attributes are not filtered out of image tags.
  62. *
  63. * @param array $allowed_tags The allowed tags and their attributes.
  64. * @return array
  65. */
  66. public function allow_lazy_attributes( $allowed_tags ) {
  67. if ( ! isset( $allowed_tags['img'] ) ) {
  68. return $allowed_tags;
  69. }
  70. // But, if images are allowed, ensure that our attributes are allowed!
  71. $img_attributes = array_merge( $allowed_tags['img'], array(
  72. 'data-lazy-src' => 1,
  73. 'data-lazy-srcset' => 1,
  74. 'data-lazy-sizes' => 1,
  75. ) );
  76. $allowed_tags['img'] = $img_attributes;
  77. return $allowed_tags;
  78. }
  79. public function add_image_placeholders( $content ) {
  80. // Don't lazyload for feeds, previews
  81. if ( is_feed() || is_preview() ) {
  82. return $content;
  83. }
  84. // Don't lazy-load if the content has already been run through previously
  85. if ( false !== strpos( $content, 'data-lazy-src' ) ) {
  86. return $content;
  87. }
  88. // Don't lazyload for amp-wp content
  89. if ( function_exists( 'is_amp_endpoint' ) && is_amp_endpoint() ) {
  90. return $content;
  91. }
  92. // This is a pretty simple regex, but it works
  93. $content = preg_replace_callback( '#<(img)([^>]+?)(>(.*?)</\\1>|[\/]?>)#si', array( __CLASS__, 'process_image' ), $content );
  94. return $content;
  95. }
  96. /**
  97. * Returns true when a given string of classes contains a class signifying lazy images
  98. * should not process the image.
  99. *
  100. * @since 5.9.0
  101. *
  102. * @param string $classes A string of space-separated classes.
  103. * @return bool
  104. */
  105. public static function should_skip_image_with_blacklisted_class( $classes ) {
  106. $blacklisted_classes = array(
  107. 'skip-lazy',
  108. 'gazette-featured-content-thumbnail',
  109. );
  110. /**
  111. * Allow plugins and themes to tell lazy images to skip an image with a given class.
  112. *
  113. * @module lazy-images
  114. *
  115. * @since 5.9.0
  116. *
  117. * @param array An array of strings where each string is a class.
  118. */
  119. $blacklisted_classes = apply_filters( 'jetpack_lazy_images_blacklisted_classes', $blacklisted_classes );
  120. if ( ! is_array( $blacklisted_classes ) || empty( $blacklisted_classes ) ) {
  121. return false;
  122. }
  123. foreach ( $blacklisted_classes as $class ) {
  124. if ( false !== strpos( $classes, $class ) ) {
  125. return true;
  126. }
  127. }
  128. return false;
  129. }
  130. /**
  131. * Processes images in content by acting as the preg_replace_callback
  132. *
  133. * @since 5.6.0
  134. *
  135. * @param array $matches
  136. *
  137. * @return string The image with updated lazy attributes
  138. */
  139. static function process_image( $matches ) {
  140. $old_attributes_str = $matches[2];
  141. $old_attributes_kses_hair = wp_kses_hair( $old_attributes_str, wp_allowed_protocols() );
  142. if ( empty( $old_attributes_kses_hair['src'] ) ) {
  143. return $matches[0];
  144. }
  145. $old_attributes = self::flatten_kses_hair_data( $old_attributes_kses_hair );
  146. $new_attributes = self::process_image_attributes( $old_attributes );
  147. // If we didn't add lazy attributes, just return the original image source.
  148. if ( empty( $new_attributes['data-lazy-src'] ) ) {
  149. return $matches[0];
  150. }
  151. // Ensure we add the jetpack-lazy-image class to this image.
  152. $new_attributes['class'] = sprintf( '%s jetpack-lazy-image', empty( $new_attributes['class'] ) ? '' : $new_attributes['class'] );
  153. $new_attributes_str = self::build_attributes_string( $new_attributes );
  154. return sprintf( '<img %1$s><noscript>%2$s</noscript>', $new_attributes_str, $matches[0] );
  155. }
  156. /**
  157. * Given an array of image attributes, updates the `src`, `srcset`, and `sizes` attributes so
  158. * that they load lazily.
  159. *
  160. * @since 5.7.0
  161. *
  162. * @param array $attributes
  163. *
  164. * @return array The updated image attributes array with lazy load attributes
  165. */
  166. static function process_image_attributes( $attributes ) {
  167. if ( empty( $attributes['src'] ) ) {
  168. return $attributes;
  169. }
  170. if ( ! empty( $attributes['class'] ) && self::should_skip_image_with_blacklisted_class( $attributes['class'] ) ) {
  171. return $attributes;
  172. }
  173. /**
  174. * Allow plugins and themes to conditionally skip processing an image via its attributes.
  175. *
  176. * @module-lazy-images
  177. *
  178. * @deprecated 6.5.0 Use jetpack_lazy_images_skip_image_with_attributes instead.
  179. *
  180. * @since 5.9.0
  181. *
  182. * @param bool Default to not skip processing the current image.
  183. * @param array An array of attributes via wp_kses_hair() for the current image.
  184. */
  185. if ( apply_filters( 'jetpack_lazy_images_skip_image_with_atttributes', false, $attributes ) ) {
  186. return $attributes;
  187. }
  188. /**
  189. * Allow plugins and themes to conditionally skip processing an image via its attributes.
  190. *
  191. * @module-lazy-images
  192. *
  193. * @since 6.5.0 Filter name was updated from jetpack_lazy_images_skip_image_with_atttributes to correct typo.
  194. * @since 5.9.0
  195. *
  196. * @param bool Default to not skip processing the current image.
  197. * @param array An array of attributes via wp_kses_hair() for the current image.
  198. */
  199. if ( apply_filters( 'jetpack_lazy_images_skip_image_with_attributes', false, $attributes ) ) {
  200. return $attributes;
  201. }
  202. $old_attributes = $attributes;
  203. // Set placeholder and lazy-src
  204. $attributes['src'] = self::get_placeholder_image();
  205. $attributes['data-lazy-src'] = $old_attributes['src'];
  206. // Handle `srcset`
  207. if ( ! empty( $attributes['srcset'] ) ) {
  208. $attributes['data-lazy-srcset'] = $old_attributes['srcset'];
  209. unset( $attributes['srcset'] );
  210. }
  211. // Handle `sizes`
  212. if ( ! empty( $attributes['sizes'] ) ) {
  213. $attributes['data-lazy-sizes'] = $old_attributes['sizes'];
  214. unset( $attributes['sizes'] );
  215. }
  216. /**
  217. * Allow plugins and themes to override the attributes on the image before the content is updated.
  218. *
  219. * One potential use of this filter is for themes that set `height:auto` on the `img` tag.
  220. * With this filter, the theme could get the width and height attributes from the
  221. * $attributes array and then add a style tag that sets those values as well, which could
  222. * minimize reflow as images load.
  223. *
  224. * @module lazy-images
  225. *
  226. * @since 5.6.0
  227. *
  228. * @param array An array containing the attributes for the image, where the key is the attribute name
  229. * and the value is the attribute value.
  230. */
  231. return apply_filters( 'jetpack_lazy_images_new_attributes', $attributes );
  232. }
  233. /**
  234. * Adds JavaScript to check if the current browser supports JavaScript as well as some styles to hide lazy
  235. * images when the browser does not support JavaScript.
  236. *
  237. * @return void
  238. */
  239. public function add_nojs_fallback() {
  240. ?>
  241. <style type="text/css">
  242. html:not( .jetpack-lazy-images-js-enabled ) .jetpack-lazy-image {
  243. display: none;
  244. }
  245. </style>
  246. <script>
  247. document.documentElement.classList.add(
  248. 'jetpack-lazy-images-js-enabled'
  249. );
  250. </script>
  251. <?php
  252. }
  253. /**
  254. * Retrieves the placeholder image after running it through the lazyload_images_placeholder_image filter.
  255. *
  256. * @return string The placeholder image source.
  257. */
  258. private static function get_placeholder_image() {
  259. /**
  260. * Allows plugins and themes to modify the placeholder image.
  261. *
  262. * This filter is not prefixed with jetpack_ to provide a smoother migration
  263. * process from the WordPress Lazy Load plugin.
  264. *
  265. * @module lazy-images
  266. *
  267. * @since 5.6.0
  268. * @since 6.5.0 Default image is now a base64 encoded transparent gif.
  269. *
  270. * @param string The URL to the placeholder image
  271. */
  272. return apply_filters(
  273. 'lazyload_images_placeholder_image',
  274. 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
  275. );
  276. }
  277. private static function flatten_kses_hair_data( $attributes ) {
  278. $flattened_attributes = array();
  279. foreach ( $attributes as $name => $attribute ) {
  280. $flattened_attributes[ $name ] = $attribute['value'];
  281. }
  282. return $flattened_attributes;
  283. }
  284. private static function build_attributes_string( $attributes ) {
  285. $string = array();
  286. foreach ( $attributes as $name => $value ) {
  287. if ( '' === $value ) {
  288. $string[] = sprintf( '%s', $name );
  289. } else {
  290. $string[] = sprintf( '%s="%s"', $name, esc_attr( $value ) );
  291. }
  292. }
  293. return implode( ' ', $string );
  294. }
  295. public function enqueue_assets() {
  296. if ( Jetpack_AMP_Support::is_amp_request() ) {
  297. return;
  298. }
  299. wp_enqueue_script(
  300. 'jetpack-lazy-images',
  301. Jetpack::get_file_url_for_environment(
  302. '_inc/build/lazy-images/js/lazy-images.min.js',
  303. 'modules/lazy-images/js/lazy-images.js'
  304. ),
  305. array( 'jquery' ),
  306. JETPACK__VERSION,
  307. true
  308. );
  309. }
  310. }