static function init() { if (is_admin()) { return; } if (!apply_filters('lazyload_is_enabled', true)) { self::$enabled = false; return; } add_action('wp_enqueue_scripts', array(__CLASS__, 'add_scripts')); add_action('wp_head', array(__CLASS__, 'setup_filters'), 9999); // we don't really want to modify anything in <head> since it's mostly all metadata, e.g. OG tags }
/** * Filter the image tag to implement lazy loading support for avatars. * * @param string $image_format * @return string */ public static function social_get_avatar_image_format($image_format) { if (class_exists('LazyLoad_Images')) { // would be great if the plugin provided an API for this, until then we'll copy the code $placeholder_image = apply_filters('lazyload_images_placeholder_image', LazyLoad_Images::get_url('images/1x1.trans.gif')); $image_format = '<img alt="%1$s" src="' . esc_url($placeholder_image) . '" data-lazy-src="%2$s" class="avatar avatar-%3$s photo %4$s" height="%3$s" width="%3$s" /><noscript>' . $image_format . '</noscript>'; } return $image_format; }
// Note: this needs to be added so that it's executed after the hook added by Jetpack add_filter('post_gallery', array(__CLASS__, 'add_image_placeholders'), 1002, 2); } static function add_scripts() { wp_enqueue_script('wpcom-lazy-load-images', self::get_url('js/lazy-load.js'), array('jquery', 'jquery-lazyload'), self::version, true); wp_enqueue_script('jquery-lazyload', self::get_url('js/jquery.lazyload.min.js'), array('jquery'), self::version, true); } static function add_image_placeholders($val, $attrs) { // Don't lazy-load if the content has already been run through previously if (false !== strpos($val, 'data-lazy-src')) { return $val; } // It's possible to filter based on gallery type here, for example if ('square' !== $attrs['type']) { return $val; } // This is a pretty simple regex, but it works // Remember to put data-lazy-src as the data attribute if you want to // serve your images through photon. They work locally too, though $val = preg_replace('#<img([^>]+?)src=[\'"]?([^\'"\\s>]+)[\'"]?([^>]*)>#', sprintf('<img${1}data-lazy-src="${2}"${3}><noscript><img${1}src="${2}"${3}></noscript>', $placeholder_image), $val); return $val; } static function get_url($path = '') { return plugins_url(ltrim($path, '/'), __FILE__); } } LazyLoad_Images::init(); }
function lazyload_images_add_placeholders($content) { return LazyLoad_Images::add_image_placeholders($content); }