In responsive web development, providing adapted media resources for different devices is a key part of improving performance and user experience. Although the HTML5 element supports media attributes (such as screen and (max-width: 800px)), this attribute only controls the visibility of the source (that is, whether to participate in rendering selection) and does not prevent the browser from preloading all resources in the tag - this is exactly the problem you encounter: the mobile terminal will still download the high-definition version of a.mp4, causing unnecessary traffic consumption.
✅ The correct solution is to delay initialization of the video source : do not set a valid src first, wait until the page is loaded and the real viewport or screen size is obtained, then explicitly specify the unique video address through JavaScript, and call .load() to trigger on-demand loading.
The following is an implementation that is lightweight, reliable, and compatible with mainstream browsers:
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Responsive background video</title>
<video id="responsiveVideo" controls muted autoplay loop playsinline>
<!-- Placeholder source to prevent early preloading -->
<source src="data:video/mp4;base64," type="video/mp4">
</source></video>
<script>
function initResponsiveVideo() {
const video = document.getElementById('responsiveVideo');
const isMobile = window.innerWidth <= 800;
//Select the video source based on the screen width (it is recommended to use window.innerWidth instead of screen.width)
const videoSrc = isMobile ? 'b.mp4' : 'a.mp4';
// Key: Set src only once, then explicitly call load()
video.src = videoSrc;
video.load(); // Trigger resource loading (not automatic playback)
// Optional: monitor window size changes (applicable to scenarios such as horizontal and vertical screen switching)
window.addEventListener('resize', () => {
if (window.innerWidth <= 800 !== isMobile) {
location.reload(); // Simple and reliable; if you need to switch without refreshing, you need to uninstall the old video and reset src load()
}
});
}
// Execute after ensuring the DOM is ready (earlier and more reliable than window.onload)
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initResponsiveVideo);
} else {
initResponsiveVideo();
}
</script>
? Key considerations:
✅ Use window.innerWidth (including scroll bars) instead of screen.width: the latter returns the physical screen width of the device (for example, iPhone 14 is 430px, but screen.width may return 980px), while innerWidth reflects the actual available viewport, which is more in line with responsive logic;
✅ Use data: URL placeholder in to completely avoid initial preloading;
✅ .load() must be called to trigger the browser to actually initiate a network request;
⚠️ If you need to support dynamic switching between horizontal and vertical screens without refreshing the page, you need to manually video.pause(), clear src, reassign and load(), but you need to pay attention to iOS Safari's restrictions on automatic playback and background loading;
? It is recommended to add the playsinline and muted attributes to the mobile version of the video to ensure that it can be played inline with mute on iOS (especially when used as a background).
This solution takes into account semantics, maintainability and performance, and is one of the best practices for modern responsive video loading.
The above is the detailed content of How to dynamically load video files of different resolutions based on screen size. For more information, please follow other related articles on the PHP Chinese website!
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
This article explains in detail how to safely and reliably dynamically switch chart types (line/bar/pie) in Chart.js, and solve the problem of Cannot read properties of undefined errors caused by mismatched data structures and rendering exceptions after type switching. The core lies in destroying old instances, deep copying configurations, and accurately rebuilding data structures by type.
This article explains in detail how to safely and efficiently extract user input from HTML forms and structure it into JavaScript objects as attribute parameters of analytics.track() to avoid hard coding and syntax errors and support flexible expansion.
This article explores why providing 2x images to high DPR devices may lower Lighthouse performance scores, and provides practical solutions to balance visual quality and real performance: including proper srcset configuration, image compression strategies, modern format selection, and load priority control.
This article explains in detail why transform: translate() combined with the keydown event cannot move elements, and provides a reliable solution based on CSS positioning and JavaScript, covering absolute positioning settings, coordinate update logic, code robustness optimization, and common pitfalls.
This article explains in detail the root cause of style failure when applying custom CSS in the WordPress Divi theme builder. It provides practical solutions for improving selector specificity, accurately positioning elements, and rational use of !important, as well as debugging tips and code optimization examples.
This article introduces a complete solution for disabling the "Next" button when the form does not meet the conditions, and using native HTML5 form validation or JavaScript dynamic control to display a friendly prompt message when the disabled button is clicked.
This article introduces how to use jQuery to dynamically switch background images after button clicks, and corrects problems such as CSS selector misuse, inline event coupling, and logical redundancy in the original code, providing a concise and maintainable interaction solution.
This article introduces how to use Python's built-in module to quickly start a lightweight HTTP server. You can access local projects in a mobile browser through the LAN without deployment, and realize real-time real-machine debugging of responsive designs.