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" data-wphbdelayedstyle="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

developer writing code at his laptop with code surrounding him in multicolored smoke
Code

Exploring the CSS Properties and Values API

The CSS Properties and Values API is an exciting part of the CSS Houdini suite of APIs that enables developers to define and register custom CSS properties directly in JavaScript. This API introduces advanced capabilities like type checking, default values, and control over whether custom properties inherit their values. These features significantly enhance the power and flexibility of CSS in modern web development.

Developer sitting outdoors at a coffer shop working on his laptop with colors swirling
Code

Exploring the CSS Paint API: Unlocking Creativity in Web Design

The web is constantly evolving, and with it, the tools available to developers and designers expand. One of the most exciting additions to modern web design is the CSS Paint API (also known as Houdini’s Paint API). This feature allows developers to create dynamic, programmatically generated images directly in CSS without the need for external assets or heavy graphical libraries.

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.