In a lazy loading scenario, how to determine if an element is within the viewport?

1. In a lazy loading scenario, how to determine if an element is within the viewport?

In lazy loading scenarios, it is a very common requirement to determine whether an element is within the viewport. It is usually used to load images, content or perform other lazy loading operations. You can use JavaScript to determine whether an element is within the viewport. Here is a specific implementation example:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Lazy Loading Example</title>
<style>
  /* 设置一些占位样式,避免页面闪烁 */
  .lazy-image {
    width: 300px;
    height: 200px;
    background-color: #f0f0f0;
  }
</style>
</head>
<body>
  <div class="lazy-image" data-src="image1.jpg"></div>
  <div class="lazy-image" data-src="image2.jpg"></div>
  <div class="lazy-image" data-src="image3.jpg"></div>
  <div class="lazy-image" data-src="image4.jpg"></div>
  <div class="lazy-image" data-src="image5.jpg"></div>

  <script>
    const lazyImages = document.querySelectorAll('.lazy-image');

    function isElementInViewport(el) {
      const rect = el.getBoundingClientRect();
      return (
        rect.top >= 0 &&
        rect.left >= 0 &&
        rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
        rect.right <= (window.innerWidth || document.documentElement.clientWidth)
      );
    }

    function lazyLoad() {
      lazyImages.forEach(image => {
        if (isElementInViewport(image)) {
          image.style.backgroundImage = `url(${image.getAttribute('data-src')})`;
          image.classList.add('loaded');
        }
      });
    }

    // 初始化时加载可见元素
    lazyLoad();

    // 监听滚动事件,当滚动时判断元素是否在视口内
    window.addEventListener('scroll', lazyLoad);
  </script>
</body>
</html>

In the above example,  getBoundingClientRect() the method is used to obtain the position information of the element, and then determine whether the top, bottom, left, and right boundaries of the element are within the viewport range. When the element is in the viewport, set  data-src the image link in its properties as the background image and add a  loaded class to mark it as loaded. By listening to  scroll events, you can dynamically determine whether an element is within the viewport during scrolling, thereby achieving a lazy loading effect.

Please note that this is just a basic example, and more details may need to be considered in actual scenarios, such as performance optimization, anti-shake throttling, etc.

2. How to determine whether the current environment is PC or mobile phone

Different methods can usually be used to determine whether the current environment is a PC or a mobile phone. Several common determination methods are listed below, and corresponding code implementation examples are provided:

1. Use media queries: Use CSS media queries to determine the device screen width to determine whether it is a mobile phone.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Device Detection</title>
<style>
  @media (max-width: 767px) {
    body {
      background-color: lightblue; /* 手机端样式 */
    }
  }
  @media (min-width: 768px) {
    body {
      background-color: lightgreen; /* PC端样式 */
    }
  }
</style>
</head>
<body>
</body>
</html>

2. Usage  navigator.userAgent: Determine the device type by checking the user agent string. Note that this approach is not very reliable as the user agent string may be modified.

if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
  console.log('手机端');
} else {
  console.log('PC端');
}

3. Use screen width: Get the screen width through JavaScript to determine the device type.

if (window.innerWidth <= 767) {
  console.log('手机端');
} else {
  console.log('PC端');
}

4. Usage  window.orientation: Check the direction of the device to determine whether it is a mobile phone or PC. This approach works on mobile devices.

if (typeof window.orientation !== 'undefined') {
  console.log('手机端');
} else {
  console.log('PC端');
}

Note that different methods may have different accuracy and applicability in different situations. All things considered, combining multiple methods may lead to a more accurate determination of device type.

3. How does the browser cache static resources?

Browsers can optimize web page loading speed by using caching mechanisms, reduce requests to the server, and provide a better user experience. Static resource caching is one of the common methods, which allows the browser to store resources locally after loading them for the first time, so that when accessing again in the future, the resources can be obtained directly from the local area without downloading them from the server again. The following are common ways for browsers to cache static resources:

1. HTTP cache header: In the communication between the browser and the server, you can control the caching strategy of static resources by setting the HTTP header field. Commonly used HTTP cache header fields are:

  • Cache-Control: This field can be used to specify the caching strategy of the resource, such as  max-age, no-cache, public, private etc.

  • Expires: This field allows you to set the expiration time of the resource, thereby telling the browser when it should re-request the resource.

  • ETag and  Last-Modified: Used to determine whether the resource has changed. If there is no change, the 304 Not Modified status can be returned.

2. Cache Manifest (AppCache): Cache Manifest is a file that defines browser caching behavior. It allows developers to clearly specify which resources need to be cached and the cached version number. Although Cache Manifest was used more in the past, due to its complexity and some problems, its use is no longer recommended.

3. Service Worker: Service Worker is a JavaScript script that acts as a proxy between the browser and the network and can intercept and process network requests. Using Service Worker can achieve more powerful cache control, including offline caching, dynamic caching, first screen acceleration, etc.

4. Browser caching algorithm: Browsers use caching algorithms to decide whether to obtain resources from the cache or to retrieve them from the server. Common caching algorithms include:

  • Strong caching: Use header fields such as Cache-Control and Expires to determine whether the resource is within the validity period.

  • Negotiation cache: Use header fields such as ETag and Last-Modified to determine whether the resource has changed.

Strong caching and negotiated caching are two common strategies. The following are specific implementation examples of these two strategies:

Strong caching example:Cache-Control Strong caching is implemented by setting the  or  field in the HTTP response header  Expires , telling the browser to obtain resources directly from the cache within a certain period of time.

// 使用 Cache-Control 设置缓存策略
// max-age 指定缓存的秒数
// public 表示资源可以被公共缓存(CDN 等)存储
// private 表示资源仅在用户私有的缓存中存储(默认值)
// no-cache 表示资源需要经过协商缓存验证后才能使用
// no-store 表示不缓存资源
response.setHeader('Cache-Control', 'max-age=3600, public');

// 使用 Expires 设置过期时间,这里设置为一个未来的日期
response.setHeader('Expires', new Date(Date.now() + 3600000).toUTCString());

Negotiation caching example:  Negotiation caching is implemented by setting ETag the and  fields in the HTTP response header  . The browser will send these values ​​​​to the server on the next request. The server determines whether the resource has changed and returns 304 Not Modified or a new resource.Last-Modified

// 生成 ETag 值,可以使用文件内容的 hash 值等
response.setHeader('ETag', '123456');

// 设置 Last-Modified 为资源的最后修改时间
response.setHeader('Last-Modified', new Date().toUTCString());

On the next request, the browser will send  If-None-Match the header field (corresponding to ETag) and/or  If-Modified-Since the header field (corresponding to Last-Modified) to the server, and the server determines whether the resource needs to be updated based on these values. If the resource has not changed, the server returns 304 Not Modified and the browser uses the cache directly.

In fact, strong cache and negotiation cache can be used together. When the strong cache fails, the negotiation cache will be further used for verification. These two strategies can be flexibly configured according to different resources and business needs.

During development, properly configuring these caching mechanisms can significantly improve web page loading speed, but it is also important to note that if the caching strategy is not configured correctly, users may see expired or incorrect resources. Therefore, it is very important to understand the principles of browser caching and different caching mechanisms, and configure them according to the actual situation.

Guess you like

Origin blog.csdn.net/qq_45635347/article/details/132515632