Boost website performance with Background Fetch API.

Have you ever wished that websites could catch up and update themselves even when you’re not actively browsing? Well, the Background Fetch API can do just that! This amazing tool allows websites to operate seamlessly in the background, keeping users up-to-date with automatic updates and fresh content checks. The convenience and ease-of-use make it a blessing for both web developers and users, allowing them to schedule necessary tasks and ensure that their websites stay current. With its adaptability to different Wi-Fi speeds and user-friendly design, this API is a game-changer in the surfing world. With more and more developers adopting this innovative tool, browsing the web will become more dynamic, reliable, and efficient.

HTML

				
					<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Background Fetch API Podcast</title>
    <link rel="manifest" href="manifest.json">
    <link rel="stylesheet" href="style.css">
    <link rel="apple-touch-icon" href="apple-touch-icon.png">
    <script crossorigin type="module" src="background.js"></script>
</head>

<body>
    <div id="wrap">
        <header>
            <h1><img decoding="async"
                    
                    alt="Background Fetch Podcast" data-src="podcast_mic.jpg" class="lazyload" src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="><noscript><img decoding="async"
                    src="podcast_mic.jpg"
                    alt="Background Fetch Podcast"></noscript></h1>
        </header>
        <!-- Progress bar -->
        <div id="progress-container">
            <div id="progress-bar"></div>
        </div>

        <!-- Button to check progress -->
        <button type="button" id="check-progress-button">Check Progress</button>
    </div>
</body>

</html>
				
			

JavaScript

				
					// Check if the service worker API is available
if ('serviceWorker' in navigator) {
	// Register the service worker
	navigator.serviceWorker.register('sw.js').then(
		function (registration) {
			console.log(
				'ServiceWorker registration successful with scope: ',
				registration.scope
			);

			// Check if the BackgroundFetchManager is available in the global scope
			if (!('BackgroundFetchManager' in self)) {
				// If it's not available, log a message to the console
				console.log('The Background Fetch API is not available');
			} else {
				// If it is available, log a message to the console
				console.log('The Background Fetch API IS available');
				// Wait for the service worker to be ready
				navigator.serviceWorker.ready.then(async (swReg) => {
					// Start a background fetch with the id 'my-fetch'
					// This fetch will attempt to download the files at the URLs below'
					const bgFetch = await swReg.backgroundFetch.fetch(
						'my-fetch',
						['groovin.wav', 'podcast_mic.jpg'],
						{
							// Provide some metadata for the fetch
							title: 'Episode 501: Code Stuff.',
							icons: [
								{
									sizes: '300x300',
									src: 'podcast_mic.jpg',
									type: 'image/jpg'
								}
							],
							// The total download size in bytes (22MB in this case)
							// This is used to provide a progress indicator for the fetch
							downloadTotal: 23048115
						}
					);

					// Function to update the progress bar
					const updateProgressBar = () => {
						if (bgFetch.downloaded && bgFetch.downloadTotal) {
							const progress = bgFetch.downloaded / bgFetch.downloadTotal;
							document.getElementById('progress-bar').style.width = `${
								progress * 100
							}%`;
						}
					};
					// Update the progress bar in response to a user action
					document
						.getElementById('check-progress-button')
						.addEventListener('click', updateProgressBar);
				});
			}
		},
		function (err) {
			// registration failed :(
			console.log('ServiceWorker registration failed: ', err);
		}
	);
} else {
	console.log('Service workers are not supported by this browser');
}

				
			

More To Explore

computer, laptop, work place-2982270.jpg
Code

Unlocking Wireless Communication: A Dive into the Bluetooth API

Wireless communication has become an integral part of our daily lives, and Bluetooth technology is at the forefront of this revolution, enabling devices to exchange data over short distances and creating a world more interconnected than ever before. At the heart of this technology lies the Bluetooth Application Programming Interface (API), a powerful tool for developers looking to harness the capabilities of Bluetooth in their applications. In this blog post, we’ll explore what the Bluetooth API is, how it works, and the possibilities it opens up for innovation in wireless communication.

lighthouse, beacon, atlantic-8578318.jpg
Code

Understanding the Beacon API: Simplifying Asynchronous Data Transfers

In today’s data-driven world, web applications often need to send data back to the server. Traditionally, this has been done using AJAX requests or similar methods. However, these techniques can come with a cost, especially when dealing with data that needs to be sent during the unload phase of a document, such as tracking and diagnostic data. This is where the Beacon API shines by allowing developers to send data to a server more reliably and efficiently.

Share This Post

small_c_popup.png

Need help?

Let's have a chat...


Login

Jump Back In!

Here at Webolution Designs, we love to learn. This includes sharing things we have learned with you. 

Register

Begin Your Learning Journey Today!

Come back inside to continue your learning journey.