【问题标题】:Dynamically load HTML from other files onto page as you scroll滚动时将其他文件中的 HTML 动态加载到页面上
【发布时间】:2019-10-01 16:26:54
【问题描述】:

编辑:我自己的问题已经回答了一半,但仍需要帮助。请参阅下面的Dynamically load HTML from other files onto page as you scroll

原帖: 我正在为会员改造一个包含可用于营销目的的图片库的网站。以前每个类别都分为子类别,导致几百页,有些页面只有一个图像。我已经放弃了子类别,并在每个类别页面上包含了所有图像。当您单击缩略图时,完整尺寸的图像会在灯箱中打开,其中包含其他信息

这对于大多数类别来说都很好,但有些类别很大并且包含几百张图片。问题是在这些页面上,大多数时候并不是所有的缩略图都会加载。我不想使用分页将这些大类别分成多个页面,而是希望在您向下滚动时动态加载更多内容。我不知道该怎么做。

jQuery load more data on scroll 上的代码 sn-p 看起来可以工作,但是有没有办法替换

html += '<p class="dynamic">Dynamic Data : This is test data.<br />Next line.</p>';

有什么东西会把file1.html的内容放在它的位置,然后是file2.html,等等?

如果没有,是否有某种方法可以创建某种文件,其中包含可以在用户向下滚动时引用和加载的缩略图位置?

YouTube video 似乎是一个不错的起点,但它需要 AJAX 调用或其他调用。我不确定这意味着什么以及它在哪里调用。

【问题讨论】:

    标签: javascript html lazy-loading dynamic-loading


    【解决方案1】:

    感谢deanhume.com,我找到了使用 IntersectionObserver 的潜在解决方案。它在 Chrome 和更新版本的 Firefox 中运行良好。

    遗憾的是,我们仍然使用 IE 11 作为我们的标准来编码我们的网站工作。我不知道为什么,但我们这样做了,我必须处理这个问题。问题是这个解决方案不适用于我用于验证的旧版本的 Firefox,也不适用于 IE 11。所以我想使用 polyfill。

    polyfill 的GitHub 页面讨论了使用<script src="https://polyfill.io/v3/polyfill.min.js?features=IntersectionObserver"></script> 来支持旧版浏览器,但它似乎不起作用。我还在网站上放置了 polyfill JavaScript 文件,并在任何其他 Javascript 之前在页头中引用它,但它似乎也不起作用。

    加载 polyfill 文件的正确方法是什么?

    引用它的第一行是:<script src="../pathto/polyfills/intersectionobserver.js"></script>

    在进入 Intersection Observer 位之前,还有一些不相关的东西;延迟加载脚本中的淡入和调用 CSS:

      <style>
        .fade-in {
          animation-name: fadeIn;
          animation-duration: 1.3s;
          animation-timing-function: cubic-bezier(0, 0, 0.4, 1);
          animation-fill-mode: forwards;
        }
    
        @keyframes fadeIn {
          from {
            opacity: 0;
          }
    
          to {
            opacity: 1;
          }
        }
    
    .centered {
       display:block;
       margin:0 auto;
    }
      </style>
    
      <script type="module">
        import LazyLoad from "../pathto/lazy-load.js";
        LazyLoad.init();
      </script>

    下面是lazy-load.js 文件。

    const defaults = {
      imageLoadedClass: 'js-lazy-image--handled',
      imageSelector: '.js-lazy-image',
      // If the image gets within 100px in the Y axis, start the download.
      rootMargin: '100px 0px',
      threshold: 0.01
    };
    
    let config,
        images,
        imageCount,
        observer;
    
    /**
     * Fetches the image for the given URL
     * @param {string} url
     */
    function fetchImage(url) {
      return new Promise((resolve, reject) => {
        const image = new Image();
        image.src = url;
        image.onload = resolve;
        image.onerror = reject;
      });
    }
    
    /**
     * Preloads the image
     * @param {object} image
     */
    function preloadImage(image) {
      const src = image.dataset.src;
      if (!src) {
        return;
      }
    
      return fetchImage(src).then(() => { applyImage(image, src); });
    }
    
    /**
     * Load all of the images immediately
     * @param {NodeListOf<Element>} images
     */
    function loadImagesImmediately(images) {
      // foreach() is not supported in IE
      for (let i = 0; i < images.length; i++) {
        let image = images[i];
        preloadImage(image);
      }
    }
    
    /**
     * Disconnect the observer
     */
    function disconnect() {
      if (!observer) {
        return;
      }
    
      observer.disconnect();
    }
    
    /**
     * On intersection
     * @param {array} entries
     */
    function onIntersection(entries) {
      // Disconnect if we've already loaded all of the images
      if (imageCount === 0) {
        disconnect();
        return;
      }
    
      // Loop through the entries
      for (let i = 0; i < entries.length; i++) {
        let entry = entries[i];
        // Are we in viewport?
        if (entry.intersectionRatio > 0) {
          imageCount--;
    
          // Stop watching and load the image
          observer.unobserve(entry.target);
          preloadImage(entry.target);
        }
      }
    }
    
    /**
     * Apply the image
     * @param {object} img
     * @param {string} src
     */
    function applyImage(img, src) {
      // Prevent this from being lazy loaded a second time.
      img.classList.add(config.imageLoadedClass);
      img.src = src;
    }
    
    let LazyLoad = {
    
      init: (options) => {
        config = {...defaults, ...options};
    
        images = document.querySelectorAll(config.imageSelector);
        imageCount = images.length;
    
        // If we don't have support for intersection observer, loads the images immediately
        if (!('IntersectionObserver' in window)) {
          loadImagesImmediately(images);
        } else {
          // It is supported, load the images
          observer = new IntersectionObserver(onIntersection, config);
    
          // foreach() is not supported in IE
          for (let i = 0; i < images.length; i++) {
            let image = images[i];
            if (image.classList.contains(config.imageLoadedClass)) {
              continue;
            }
    
            observer.observe(image);
          }
        }
      }
    };
    
    export default LazyLoad;

    为了以防万一,页面上的图像代码示例:

    &lt;img class="js-lazy-image" data-src="url/members/thumbs/ab_banff_np.jpg" alt="rockies, rocky mountains, trees, summer" aria-describedby="image_g2"&gt;

    【讨论】:

      【解决方案2】:

      现在您可以使用标签 loading="lazy" 在 html 上进行本地延迟加载

      例子:

      <img src="image.png" loading="lazy" width="200" height="200">
      

      更多信息:https://css-tricks.com/native-lazy-loading/

      【讨论】:

      • 这将是完美的,只是它似乎只受 Chrome 支持。
      【解决方案3】:

      要在 Javascript(并使用 jQuery)中加载更多内容,您可以使用以下命令:

      $.ajax("path/to/your/file/file1.html")
        .done((data) => {
          $('body').append(data);
        });
      

      这是做什么的:

      1. 获取file1.html的内容
      2. 将内容添加到您当前网站的正文中

      更多信息:

      【讨论】:

      • 那段代码去哪儿了?在页面标题中的
      • 它位于外部 JS 脚本或内联
      猜你喜欢
      • 1970-01-01
      • 2017-03-21
      • 1970-01-01
      • 2017-05-06
      • 1970-01-01
      • 2018-07-28
      • 1970-01-01
      • 1970-01-01
      • 2011-10-04
      相关资源
      最近更新 更多