LazyLoad Divi Rows and Sections

With this code, there will be added automatically lazyload-references to Divi Rows and Sections, as well as its inner content. This code is in Alpha and should be used carefully, although it’s currently in use on our main blog, www.gooloo.de, with no issues.

function divi_lazy_load_rows() {
    if (!is_admin()) {
        add_filter('the_content', 'add_lazy_load_attributes');
        add_action('wp_enqueue_scripts', 'enqueue_lazy_load_script');
        add_action('wp_head', 'add_lazy_load_css');
    }
}
add_action('init', 'divi_lazy_load_rows');

function add_lazy_load_attributes($content) {
    $content = preg_replace('/<img(.*?)src=/i', '<img$1data-src=', $content);
    $content = preg_replace('/<(div|section)(.*?)style="(.*?)background-image: url\((.*?)\)(.*?)"/i', '<$1$2style="$3background-image: none;$5" data-src="$4"', $content);
    $content = preg_replace('/<iframe(.*?)src=/i', '<iframe$1data-src=', $content);
    $content = preg_replace('/<(div|section)(.*?)class="(.*?)et_pb_row(.*?)"/i', '<$1$2class="$3et_pb_row$4" style="opacity: 0; transition: opacity 0.5s ease-in;"', $content);
    return $content;
}

function enqueue_lazy_load_script() {
    wp_enqueue_script('jquery');
    wp_add_inline_script('jquery', '
        jQuery(document).ready(function($) {
            var lazyLoadRows = function() {
                $(".et_pb_row:not(.lazy-loaded)").each(function() {
                    if ($(this).offset().top < $(window).scrollTop() + $(window).height() + 200) {
                        $(this).addClass("lazy-loaded");
                        $(this).find("[data-src]").each(function() {
                            var src = $(this).attr("data-src");
                            if (src) {
                                if ($(this).is("img")) {
                                    $(this).attr("src", src);
                                } else {
                                    $(this).css("background-image", "url(" + src + ")");
                                }
                            }
                        });
                        $(this).find("iframe[data-src]").each(function() {
                            var src = $(this).attr("data-src");
                            if (src) {
                                $(this).attr("src", src);
                            }
                        });
                    }
                });
            };
            
            $(window).on("scroll", lazyLoadRows);
            $(window).on("resize", lazyLoadRows);
            lazyLoadRows();
        });
    ');
}

function add_lazy_load_css() {
    echo '<style>
        .et_pb_row.lazy-loaded {
            opacity: 1 !important;
        }
    </style>';
}

Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *