Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Performance optimization:JavaScript Performance Optimization for Mobile Adaptation to Improve Page Responsiveness #308

Merged

Conversation

LofiSu
Copy link
Contributor

@LofiSu LofiSu commented Aug 21, 2024

<script>
  // Execute the callback function when the DOM content is fully loaded and parsed
  document.addEventListener('DOMContentLoaded', () => {
    // Define a function to update media content (video or image)
    function updateMedia() {
      // Get the element with class 'media-container'
      const mediaContainer = document.querySelector('.media-container');
      
      // Check the current window width
      if (window.innerWidth <= 768) {
        // If the window width is less than or equal to 768 pixels (typically mobile devices), insert an image
        mediaContainer.innerHTML = `
          <div id="background-image" class="image-background" 
               style="background-image: url('https://img.alicdn.com/imgextra/i1/O1CN01U3PG171Wiz4B85TGK_!!6000000002823-0-tps-2388-1168.jpg');"></div>
        `;
      } else {
        // If the window width is greater than 768 pixels (typically PC), insert a video
        mediaContainer.innerHTML = `
          <video
            id="background-video"
            autoplay
            muted
            loop
            class="video-background"
            poster="https://img.alicdn.com/imgextra/i1/O1CN01U3PG171Wiz4B85TGK_!!6000000002823-0-tps-2388-1168.jpg"
          >
            <source
              src="https://cloud.video.taobao.com/vod/play/V3VEOGxHS3IxSU5wWkFYeTFuZU4wdHJ2eXloK1g1aXlXV0pvNU0zVjhmYTZQZWw1SnpKVVVCTlh4OVFON0V5UUVMUDduY1RJak82VE1sdXdHTjNOaHc9PQ"
              type="video/mp4"
            />
          </video>
        `;
      }
    }

    // Call the updateMedia function initially when the page loads to set the correct media content
    updateMedia();

    // Listen for window resize events and call updateMedia to update media content
    window.addEventListener('resize', updateMedia);
  });
</script>

Detailed Explanation of the Code

  1. document.addEventListener('DOMContentLoaded', () => {...});

    • This sets up an event listener to handle the DOMContentLoaded event. This event is triggered when the HTML document has been completely loaded and parsed. At this point, JavaScript code can safely manipulate DOM elements.
  2. function updateMedia() {...}

    • Defines a function named updateMedia that decides whether to insert an image or a video based on the current window width. This function is the core part for dynamically adjusting the page content.
  3. const mediaContainer = document.querySelector('.media-container');

    • Uses document.querySelector to get the first element with the class media-container and stores it in the variable mediaContainer. This element will be used to insert or update media content.
  4. if (window.innerWidth <= 768) {...}

    • Checks if the window width is less than or equal to 768 pixels. This is typically used to determine if the device is a mobile device (based on common screen widths).
  5. mediaContainer.innerHTML = ...

    • Dynamically updates the content of the mediaContainer element based on the window width check:
      • For Mobile: Inserts a div element with a background-image style set to the image URL, showing a background image.
      • For PC: Inserts a video element with attributes (autoplay, muted, loop), and includes the video source (source element).
  6. updateMedia();

    • Calls the updateMedia function when the page initially loads to ensure the correct media content is inserted based on the current window width.
  7. window.addEventListener('resize', updateMedia);

    • Listens for window resize events (resize) and calls the updateMedia function to dynamically update the media content according to the new window size. This ensures that media content updates when the user resizes the browser window.

Summary

This script dynamically inserts media content (image or video) based on the screen size, improving the responsiveness and user experience of the page. It checks and updates media content both on initial page load and when the window size changes, ensuring optimal display on different devices.

Dynamic Element Insertion with JavaScript

By using JavaScript to determine screen width and decide whether to insert a video or an image, you can completely avoid loading video files on mobile devices and load appropriate images instead.

Benefits

  • Performance Optimization: Avoids loading unnecessary video files on mobile devices, saving bandwidth and improving page load speed.
  • Flexibility: Dynamically adjusts the displayed content based on screen size, enhancing user experience.

Additional Optimizations

  • Lazy Loading: Implement lazy loading for images and videos to further optimize performance, especially when these elements are outside the viewport.
  • Server-Side Rendering (SSR): Determine which media element to insert on the server side based on user-agent information, avoiding delays caused by client-side JavaScript execution.

Using these methods, you can effectively handle media adaptation for mobile and PC platforms, improving page responsiveness and user experience.

Copy link
Collaborator

@Hazel0928 Hazel0928 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@Hazel0928 Hazel0928 merged commit b5002a3 into higress-group:develop-astro-higress Aug 22, 2024
2 checks passed
Tinie13 pushed a commit to Tinie13/higress-group.github.io that referenced this pull request Sep 24, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants