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 type="wphb-delay-type" crossorigin data-wphb-type="module" src="background.js"></script>
</head>

<body>
    <div id="wrap">
        <header>
            <h1><img decoding="async"
                    src="podcast_mic.jpg"
                    alt="Background Fetch Podcast"></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>
<script type="text/javascript" id="wphb-delayed-styles-js">
			(function () {
				const events = ["keydown", "mousemove", "wheel", "touchmove", "touchstart", "touchend"];
				function wphb_load_delayed_stylesheets() {
					document.querySelectorAll("link[data-wphbdelayedstyle]").forEach(function (element) {
						element.setAttribute("href", element.getAttribute("data-wphbdelayedstyle"));
					}),
						 events.forEach(function (event) {
						  window.removeEventListener(event, wphb_load_delayed_stylesheets, { passive: true });
						});
				}
			   events.forEach(function (event) {
				window.addEventListener(event, wphb_load_delayed_stylesheets, { passive: true });
			  });
			})();
		</script></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

Code

Exploring the Broadcast Channel API: Inter-Tab Communication

Intercommunication between different contexts (like tabs, iframes or workers) of the same origin has often been a challenge. With the Broadcast Channel API, developers now have a powerful tool to easily communicate between browsing contexts. In this blog post, we’ll dive deep into the capabilities of the Broadcast Channel API, exploring its features, use cases, and how it can be effectively implemented in your projects.

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.

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.