Blog>
Snippets

Conditional Resource Preloading

Demonstrate how to conditionally preload heavy resources (e.g., images, videos) based on network conditions and device capabilities, to improve user experience on slower connections.
if ('connection' in navigator) {
  if (navigator.connection.saveData === true ||
      ['slow-2g', '2g'].includes(navigator.connection.effectiveType)) {
    console.log('Use lower quality resources due to saveData mode or slow connection');
  } else {
    document.head.innerHTML += '<link rel="preload" as="image" href="heavy-image.jpg">';
    console.log('Preloading heavy resources');
  }
} else {
  console.log('Browser does not support the Network Information API');
}
This code checks if the browser supports the Network Information API and if the user has enabled data saver mode or is on a slow connection (slow-2g, 2g). If so, it logs a message to use lower quality resources. Otherwise, it dynamically appends a preload link for a heavy image to the head of the document, indicating to preload the heavy image.