簡體   English   中英

使用 javascript 的延遲加載 Elementor 部分

[英]Lazy Load Elementor Section with javascript

有沒有辦法用 javascript 延遲加載 wordpress 元素或部分,以便首先加載頁面在一秒鍾內,然后所有部分依次加載。

我來到這里,因為我的部分包含一個短代碼,其中包含一些沉重的 HTML,從某種意義上說,由於 JavaScript,它會大大減慢頁面加載速度,因為這些是slick.js滑塊,我在我家有三個滑塊頁。 我說的 slider 插件是Woo 產品 Slider 和帶有類別的 Carousel

我現在的想法是將短代碼包裝到我自己的短代碼中,並確保觸發 JS 來初始化滑塊,如下所示:

[heavy onload="wcpscwc_product_slider_init()"][wcpscwc_pdt_slider cats="133" limit="12"][/heavy]

繁重的簡碼是這樣實現的:

/**
 * Heavy
 * 
 * Lazy load heavy elements
 */
add_shortcode('heavy', function ($atts = [], $content = null) {
    if (
        strpos($_SERVER['REQUEST_URI'], '/post.php') !== false ||
        strpos($_SERVER['REQUEST_URI'], 'elementor') !== false
    ) {
        return $content;
    } else {
        $atts = shortcode_atts([
            'offset' => '100',
            'onload' => ''
        ], $atts);

        ob_clean();
        ob_start();

        $id = wp_generate_uuid4();
?>
        <div id="<?php echo $id; ?>" class="heavy-container" data-offset="<?php echo $atts['offset']; ?>" onload="<?php echo $atts['onload']; ?>"></div>
        <script type='text/javascript'>
            (function() {
                window.heavy = window.heavy || {};
                window.heavy["<?php echo $id; ?>"] = <?php echo json_encode(do_shortcode($content)); ?>;
            })();
        </script>
<?php
        return ob_get_clean();
    }
});

它只是存儲編碼在全局heavy object 中的 HTML,一旦您使用頁面底部的此 JS 將其相應的 div 滾動到視圖中,就可以進行初始化(確保它在可能的最后一刻執行):

(function () {
  window.heavy = window.heavy || {};
  var heavyContainers = document.querySelectorAll(".heavy-container");
  var attemptInitHeavyElements = function () {
    var heavyContainersToLoad = [];
    heavyContainers.forEach(function (container) {
      if (
        window.heavy[container.id] &&
        container.getBoundingClientRect().top - container.dataset.offset <
          window.innerHeight
      ) {
        heavyContainersToLoad.push(container);
      }
    });
    if (heavyContainersToLoad.length) {
      heavyContainersToLoad.forEach(function (container) {
        container.innerHTML = window.heavy[container.id];
        container.onload && container.onload();
        delete window.heavy[container.id];
        container.classList.add("heavy-container--loaded");
      });
    }
  }
  document.addEventListener("scroll", attemptInitHeavyElements);
  attemptInitHeavyElements();
})();

是的,此解決方案不適用於部分,但它應該適用於您可以封裝在短代碼中的任何內容。 它不是很漂亮,並且會干擾其他延遲加載插件,但它很實用,甚至可以與W3Cache一起使用。

這肯定不適用於任何內容,您必須制定所需的步驟並將它們放入短代碼的onload事件中,但我希望它對任何人都有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM