Skip to content

Instantly share code, notes, and snippets.

@igorbenic
Last active August 21, 2017 15:27
Show Gist options
  • Select an option

  • Save igorbenic/b1aa08c2faa5de918c10d706c098d3f0 to your computer and use it in GitHub Desktop.

Select an option

Save igorbenic/b1aa08c2faa5de918c10d706c098d3f0 to your computer and use it in GitHub Desktop.
How to Optimize the Divi Gallery Module | http://www.ibenic.com/optimize-divi-gallery-module
<?php
/**
* Replacing the original image source with a placeholder
* Placing the original source under attribute data-original
* @param array $img_match
* @return string
*/
function my_preg_lazyload($img_match) {
$img_replace = $img_match[1] . 'src="https://via.placeholder.com/380x250?text=Image%20Loading" data-original' . substr($img_match[2], 3) . $img_match[3];
$img_replace = preg_replace('/class\s*=\s*"/i', 'class="lazy ', $img_replace);
$img_replace .= '<noscript>' . $img_match[0] . '</noscript>';
return $img_replace;
}
(function($){
$(document).ready(function(){
// Show the first image of each gallery
$(".et_pb_gallery_items").each( function(){
var first_image = $(this).find('.et_pb_gallery_item').eq(0).find('img');
var orig = first_image.attr('data-original');
first_image.attr("src", orig);
});
});
})(jQuery);
(function($){
$(document).ready(function(){
// ...
// Trigger this before the next gallery image loads
$(document).on( 'simple_slider_before_move_to', function( $arg, $arg2 ){
var $original_img = $arg2.next_slide.find('[data-original]');
var $orig = $original_img.attr('data-original');
$original_img.attr("src", $orig);
});
});
})(jQuery);
<?php
add_filter( 'do_shortcode_tag', 'my_gallery_shortcode', 99, 4 );
/**
* Replacing images SRC in Divi Gallery
* @param string $output
* @param string $tag
* @param array $attr
* @param array $m
* @return string
*/
function my_gallery_shortcode( $output, $tag, $attr, $m ) {
if( 'et_pb_gallery' == $tag ) {
// This script can be used just for these if you don't have another JavaScript file
if( ! wp_script_is( 'my-gallery-enh' ) {
wp_enqueue_script( 'my-gallery-enh', get_stylesheet_directory_uri() . '/assets/public/gallery.js', array( 'jquery' ), '1.0', true );
}
return preg_replace_callback('/(<\s*img[^>]+)(src\s*=\s*"[^"]+")([^>]+>)/i', 'my_preg_lazyload', $output );
}
return $output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment