Quantcast
Jump to content

Improving web performance with responsive design


Recommended Posts

2021-06-08-01-banner.jpg

Making your web app adaptive following responsive design techniques can improve your performance score, here is how.

The benefits of applying responsive design include boosting your SEO, having a better user experience on different devices, and making your website more accessible, but did you know that making your web app adaptive to different viewports can also improve your web performance score? In previous articles, we explained the current status of responsive design including dark mode and responsive design for foldables, and we even share some insights about its future, now let’s deep dive into how web performance is related to an optimized look and feel.

Web Performance Metrics

The first step to improving something is to measure it! Being aware of what metrics that we should collect to later compare results that will show us which aspects of our web app needs more work. When it’s about web performance, we can use any of our favourite browser devtools, in this case, I will be using Lighthouse. There are many metrics to consider but when it’s about responsive design, Cumulative Layout Shift and CSS Optimization play an important role.

Cumulative Layout Shift

The first metric that we will use to achieve a responsive design is Cumulative Layout Shift, this is really important because is a user-centric metric and measures visual stability. How many times have you been on a website and suddenly you experience some changes in the layout? It's like the page moves by itself! This can lead to click on the wrong thing or lose your place whilst reading. Annoying right? We don’t want to offer that bad user experience! Let me show you an example and how we fixed it.

Last year we build the first prototype of Samsung Global Goals PWA in collaboration with the United Nations, our mission was to bring the native app to other platforms because we believe in the power of the outreach of the World Wide Web. This web app basically loads dynamic content like cards with images and text. One of our main goals was to deliver a fast app even if the connection was not reliable, then we tested the web app using a low bandwidth connection to see how it goes. The results were not bad but as we had dynamic images loading, our cards changed the size while it completes the download of the resources. This looks really bad, therefore it deserves a fix (and an apology to the user).

Cards while loading with a low connection.Cards while loading with a low connection.

How do we fix this? It’s pretty simple, if you have the same problem using images, always set up height and width.

Width and height attribute added to img elementWidth and height attribute added to img element

0*MJd4zDugmD_pCqw5

If you have dynamic content like us on your web app or let’s say that you will show ads later, make sure to use placeholders specifically for this content. This is what we did, we used a placeholder with a background colour that matches the card and image, so images will load and cards won't move at all. Websites should strive to have a CLS score of 0.1 or less, by doing this we went from 0.33 to 0! Besides that, remember if your image is in a container you can use CSS to adjust the image to it by using height: auto and width: 100%

CSS Optimization

We usually rely on external CSS libraries to achieve a responsive design, there are a few things that we have to keep in mind to don’t mess up our performance if we do this. The techniques related to CSS optimization include reducing render-blocking CSS, eliminating unused CSS rules, and minify CSS.

I will focus on removing unused CSS since it’s one of the most common issues that we need to improve when using external resources. Actually, you can check if you have unused CSS on Lighthouse, for example, here is telling us that we are not using around 95% of our CSS, this is a lot!

Unused CSS metric on lighthouseUnused CSS metric on lighthouse

How to detect unused CSS and remove it

If you are using an external library check if you have the option to export just the components that you will use instead. Another option is taking a look at how your web app is using the resources. You can try this on Chrome Dev tools, press CTRL + SHIFT +Pto open the command line, and type coverage. A new tab will appear where you will find how much percentage of your resources are being used. For example, the following CSS library has almost 40% of unused lines, same with other resources. If you click on a particular one you can even see which lines are used or unused indicated by different colors.

1*K3a0VDMAcSv49x0dJL8jyA.gif

There are several libraries that can detect unused CSS and reduced your CSS file size, like Purify CSS, which is a JS library that you can install with npm or directly use purify CSS online. It will not only show you the amount of unused code it will also create a new CSS file with just the code that you currently need.

🚀Performance and Responsive Design are correlated

Just in case that you were not clear about the multiple benefits of responsive design, now you can add one more to this list: making your web app faster and more performant. Which are your favorite performance tools?

View the full blog at its source

Link to post
Share on other sites


Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
  • Similar Topics

    • By STF News
      (From left) Engineers Kwanyoung Kim and Seungsan Han, and designer Sungdo Son – members of Samsung Electronics’ Visual Display Business, and the developers behind the company’s new solar cell-powered remote control and environmentally friendly TV packaging.
       
      Did you know that out of the more than 50 million1 tons of electronics that are thrown away each year, only a mere 17 percent is eventually recycled? Most of this ‘e-waste’ ends up polluting the environment by sitting in landfills or being incinerated. With annual e-waste expected to reach as much as 74 million tons by 2030, the global community has started taking steps to reduce consumption and minimize waste.
       
      Driven by a desire to keep our planet clean for generations to come, Samsung Electronics regularly engages in eco-conscious efforts that are helping to establish a circular economy. The company is constantly exploring ways to reduce its products’ impact on the environment, including increasing products’ lifespans and spearheading efforts to recycle their resources.
       
      In celebration of Earth Day 2021 (April 22), this special series will shine a light on Samsung initiatives that are paving the way for a circular economy. Our first article took a closer look at how the company’s recycling campaigns are giving old phones new life. Here, we’ll examine how Samsung’s Visual Display Business is making its TVs more sustainable by adopting eco-friendly packaging and solar-cell-powered remote controls.
       
      Today, innovation no longer focuses solely on creating a more convenient and efficient future, but a sustainable one as well. As such, leaders in the fields of science and technology are devoting their utmost efforts to making their products eco-friendly without compromising on performance.
       
      Samsung consistently pursues innovations that allow it to make its products more environmentally friendly. Recently, the company added an eco-friendly touch to one of consumers’ favorite appliances by developing a remote control that’s made using renewable plastic and powered by photovoltaic energy rather than disposable batteries, as well as TV packaging that can be reused as small furniture. Samsung Newsroom recently sat down with members of the team behind the innovations that are making Samsung TVs more sustainable.
       
       
      A Solar Cell-Powered Remote Control That Charges Itself Using Photovoltaic Energy
      Even if you have a nice, big, high-performance TV in your living room, you won’t be able to fully enjoy its countless channels and manage the volume and other features without a remote control. When exploring ways to make remote controls more eco-conscious, Samsung’s developers focused their attention on disposable batteries.
       
      “Supposing that a typical TV is used for around seven years, changing the batteries in its remote just once a year would mean that 14 batteries would get used and thrown out,” said Kwanyoung Kim, an engineer. If we apply that number to Samsung Electronics’ expected annual global TV sales, it amounts to approximately 99 million discarded batteries. If we apply it to annual TV sales overall, it adds up to nearly 3.1 billion batteries.2
       
      ▲Over the course of a TV’s lifetime, a solar cell-powered remote control could effectively prevent up to 99 million AA batteries from being used and discarded.
       
      Rather than using disposable batteries in the remote, the engineers decided to go with a self-charging battery instead. Many charging methods were considered, including one that harnessed the kinetic energy that’s created when the remote is shaken, and one that utilized the vibrational energy that’s created when the microphone picks up sounds. As Kim explained, at the end of the day, the optimal charging solution turned out to be a solar cell.
       
      “Even when we aren’t watching our TV or using our remote, we usually have the lights on, except when we are sleeping. This makes light an easily accessible charging solution,” said Kim. “If we substituted disposable batteries with self-charging solar cell batteries like the one we’ve developed, it would amount to reducing up to around 6,000 tons of greenhouse gas emissions per year.”
       
      How exactly does the remote control generate energy from the fluorescent lights in our living rooms? Put simply, its solar panel takes in photons from light, which react with the electrons in the solar cells to create electricity. The difference between outdoor panels and indoor panels is the spectrum of light being used. “You can’t get as much light indoors compared to sunlight,” added Kim, “so we decided to utilize solar cells that generate energy even in low-light indoor environments.”
       
       
      Increasing Electricity Efficiency Makes Solar Cell-Powered Remote Controls Possible
      Because the amount of electricity that could be created by converting light energy simply wasn’t enough, it would be impossible to generate enough energy for the remote control using solar cells alone. This led the engineers to create a low power remote control instead of searching for ways to increase energy production.
       
      The engineers succeeded in increasing the remote control’s energy efficiency by reducing its power consumption by 86 percent.3 They did this by taking users’ TV watching patterns, the number of times they pressed their remote control’s buttons, and usage time into account. As Kim explained, the solar cells in the final product “can provide up to 70 percent of the power used by the remote control.”
       

       
      Making the design of the typical TV remote control, which has remained unchanged until now, more sustainable was no simple task. The color of the solar panel was already determined, so it was difficult to apply various colors to the remote control’s design. One of the team’s key concerns was that the remote control’s panel would need to be raised up high in order to be charged via light. “The solar panel itself is gray, so if we used a color other than black for the battery, it wouldn’t go well with the overall product design,” said Kim. “We also needed the design to encourage consumers to do their part to help the environment.”
       
      The remote control is so small that you could ask whether it even needs to be energy-saving. If you asked the developers, they would tell you that, because the final product is even more eco-conscious than they anticipated, its design was undoubtedly meaningful and their efforts were worthwhile. Their ultimate goal is to develop a solar cell-powered remote control that is capable of charging itself up to the full amount of energy that it needs.
       
      “TV remote controls are frequently used products, and our aim is to create the kind of remote that offers users meaningful value, and can be a deciding factor when purchasing a TV,” said Kim.
       
       
      Use of Recycled Plastic Materials Contributes to a Huge Reduction in CO2 Emissions
      Solar panel technology isn’t the only thing that makes Samsung’s new remote control especially eco-friendly. Indeed, the plastic material used to create this roughly 40g device is comprised of 28 percent recycled plastic. Samsung has been utilizing recycled plastic in its products for a long time, and has received various certifications for its eco-friendliness. Now, the company has expanded its scope by applying recycled materials to accessories like remote controls as well.
       
      Recycled plastic is enticing because it reuses resources, but not everything about it comes easily. For a start, unit prices go up during the manufacturing process. While Samsung’s VD business does utilize plastic waste that has been collected in Korea, the volume is so small that additional resources need to be imported from overseas. This process causes costs to go up by five percent at the least, and 10 percent at the most.
       
      “The amount of plastics used by Samsung Electronics’ VD Business alone is 250,000 tons,” said Seungsan Han, an engineer and colleague of Kim’s. “Even substituting 10 to 30 percent of that with recycled plastics would require 30,000 to 70,000 tons.”
       

       
      Despite those costs, Samsung is committed to increasing its usage of recycled materials based on their clear eco-conscious benefits. According to Life Cycle Assessments (LCA), a methodology for assessing environmental impact, products made using approximately 28 percent recycled plastics emit 31 percent less CO2 than products made from non-recycled plastics.4 In an effort to maximize its use of eco-friendly materials, Samsung also explores ways to utilize waste that has been thrown indiscriminately into the sea. “Twenty percent of the waste that gets thrown into the sea is made of Polyethylene terephthalate,” said Han. “The marine waste plastic obtained here is called OBP (Ocean Bound Plastic) material, which can be applied to the exteriors of electronics. Using OBP in this way helps discourage marine pollution while promoting efforts to protect the environment.”
       
       
      More Interest in Eco-Friendliness Widens the Range of Recycled Materials
      Samsung has long practiced eco-conscious business management, and has been developing eco-conscious products and technologies for several years. As a result, the company is now capable of producing high-quality products using recycled materials, while keeping unit prices at manageable levels.
       
      ▲ Samsung’s eco-friendly solar cell-powered remote control.
       
      Samsung currently utilizes recycled plastics when producing many products, including not just its new, solar cell-powered remote control, but other remote controls as well. Eco-conscious materials are used in the company’s monitors, signage stands, and back covers, too. “In the future, the use of recycled materials will be expanded to include more Samsung TV products,” said Han. “With 2030 being the year when we hope to reach our ultimate achievement, we will keep increasing our use of recycled plastics each year.”
       
       
      Eco-Packaging: What Would Be Trash Becomes Small Furniture
      Increasing products’ efficiency and using recycled materials are clear ways to become more eco-conscious. Now, efforts are being made to address the eco-friendliness of products’ packaging, which would usually be thrown away. Allowing consumers to use their TV’s packaging to make small furniture, the eco-packaging that Samsung introduced in 2020 is a perfect example of this point.
       
      The TVs’ eco-packaging first began as a project of C-Lab, Samsung’s in-house startup incubation program. The C-Lab developers were wondering how best to recycle TVs’ packaging when they noticed that Serif TV users were placing their set-top box, small furniture, and electric devices under their TV as if it were a cabinet. This led them to the idea to use TVs’ strong cardboard packaging to make small, long-lasting furniture, which became the foundation for a new type of ‘eco-packaging.’
       

       
      Eco-packaging’s manufacturing process is mostly the same as that of other packaging, but also includes the application of a dotted pattern that helps users assemble the packaging into furniture. Although adding the dotted patterns sounds easy and could be achieved by simply printing graphics, the task presented some difficulties as well. The thicknesses and specifications of the cardboard boxes varied slightly by country, which entailed continuous communication with various parties. “Although we faced many difficulties when making the eco-packaging, we managed to do a great job thanks to the efforts of many people, including the Graphics Team,” said Sungdo Son, a Samsung Electronics designer.
       
       
      Easy to Make, Beautiful to Behold
      Simple steps for assembling the furniture can be found on the website embedded in the QR code printed on the side of the eco-packaging. “The website, which was recently updated, not only offers instructions on how to make furniture, but also provides an overall introduction to eco-packaging with relevant videos,” said Son. “We’ve arranged the website based on difficulty, so users can choose the type of furniture they’d like to make depending on their skill level.”
       

       
      The cardboard furniture displayed on the website are all items that were chosen by designers who actually tried making them themselves. “When we focused on aesthetics, it became difficult to make the furniture, and the designs often didn’t end up being very useful,” said Son. “On the other hand, when the furniture was too easy to make, it didn’t look so great. We also got rid of any furniture designs that could potentially create safety issues.”
       
      Samsung’s safety- and environmentally conscious eco-packaging has gone beyond lifestyle TVs and is now being applied across the company’s entire 2021 TV lineup. The employees involved in developing the eco-packaging hope that it will eventually reach much more consumers, and will help encourage them to contribute to environmental conservation in any way they can. “Samsung is known for producing technologically advanced products, but I want others to know that Samsung also believes that little things like these matter, and we are working on them as well,” said Son.
       

       
       
      1 According to the Global E-waste Monitor 2020 by Global E-waste Statistics Partnership (GESP), the amount of electronic waste in 2019 was 53.6 million metric tons (Mt).
      2 2020 global annual TV sales figures are based on findings from market research firm OMDIA.
      3 Compared to remote controls of Samsung Electronics’ 2020 TV models.
      4 Emissions of general plastics: 2.15 kg CO2/kg; emissions of recycled plastics: 1.47 kg CO2/kg; a reduction in CO2 emissions of 31 percent (based on a Lotte Chemical LCA evaluation)
      View the full article
    • By STF News
      As more and more consumers gravitate towards streaming services, TVs are evolving into the device of choice for those who desire larger, higher-quality screens, more immersive gaming experiences and at-home exercise functionalities, among other features. These days, Smart TVs are particularly in the spotlight given that users can enjoy a whole array of different content on them with just an Internet connection.
       
      Samsung Electronics unveiled its first Samsung Smart TV in 2011. In 2015, the company introduced its Tizen OS and has continued making progress in this field with a view to provide users with differentiated services. But how exactly has Samsung adapted to recent changes in the way people are consuming content? What efforts have been made to advance Samsung Smart TVs into becoming better platforms? Samsung Newsroom spoke to Seline Sangsook Han, Vice President of Service Business Team, Visual Display Business at Samsung Electronics, to learn more.
       

       
       
      Q. Recently, a growing number of consumers have been putting more value on user experience instead of TV price or design when purchasing TVs. What is driving this change in purchase trends?
       
      In the past, a user’s media experience came just from watching the broadcast programs provided by their set-top box or TV tuner. Under these conditions, the resolution of the TV’s screen and the way it matched the space it was placed in was the top priority for those purchasing TVs.
       
      However nowadays, the way we consume media content is diversifying and the content itself is becoming richer and more varied. As such, users are now prioritizing their own unique experiences and considering how their devices fit into their own individual tastes and environments. On top of this, TVs are evolving into smart devices, meaning that the scope of their experience offering is expanding. All of these factors are driving the current change in trends.
       
       
      Q. Are industry insiders noting an experience-centric user trend?
       
      Samsung Electronics started to provide smart TVs in 2011 and emerged as the industry leader. However, back then, users were less involved with the smart TV trend and there were few partners active in the market. These days, smart TVs are becoming increasingly important, and Samsung’s Smart TV has become a pivotal partner. Trend analysis shows us that, today, people are enjoying binge-watching shows more than they are watching shows in real-time. According to our internal research, people are spending more time watching Over-the-top (OTT) content on Samsung Smart TVs than they are watching live content. U.S. users subscribe to an average of three OTT services, demonstrating that smart TV markets are on the rise globally.
       
       
      Q. How is the Samsung Smart TV adapting to these changing trends?
       
      Samsung is committed to keeping up with changing trends and the Samsung Smart TV has gone through extensive research for better user experiences. One of our top priorities has been figuring out how to provide users with the best possible experience of finding and enjoying the content they want to consume.
       
      Samsung offers a content forwarding discovery service called Universal Guide to help consumers make choices easily by recommending content tailored to individual user preferences. In addition, Samsung TV Plus is available for users to enjoy a variety of channels on – news, entertainment, movies, TV shows and more. This is a free TV service, with no strings attached.
       
      On top of this, users can also appreciate leading art works on their TV via the Art Store of lifestyle TV The Frame and enjoy indoor workouts through Samsung Health, a functionality that was released this year. These services particularly benefit those who have experienced unexpected changes in their day-to-day lives this year and are thus finding themselves staying at home more.
       

       
       
      Q. What does it take to make a great TV platform?
       
      Nobody can make a great platform while working alone. When we appreciate what an ecosystem means, a great platform can emerge.
       
      From the perspective of partners, high quality technologies and user convenience should be ensured. Furthermore, for the sake of a platform’s users, enriching and useful content and user convenience are essential features, as these factors are what drive an engaging user experience. Samsung, as a platform provider, needs to create a viable marketplace with which to build a mutually beneficial business model in order to drive continued investment and partner growth and ultimately improve user satisfaction. At the end of the day, relentless efforts driving strategies tailored to one’s platform is what can bear fruit.
       
       
      Q. What makes the Samsung Smart TV unique in terms of its platform?
       
      The Samsung Smart TV was created as a television device. Over the past 14 years, Samsung has been ranked number one in the TV industry, and during these years, Samsung has continued to build its leadership across the markets as well as cultivated a robust user base. As a service platform, the Samsung Smart TV was not a leader at all in the beginning. Thanks to Samsung’s market leadership and product offering as a TV manufacturer, we have been able to reach users around the world, and this user base helped the company attract partners. Considering that TVs are a home necessity and play a pivotal role in consumers’ media consumption, the Samsung Smart TV has an unbeatable position and capabilities in terms of product manufacturing and supply, user experience design and ecosystem operation based on its own platform.
       
      These days, fewer people are watching TV in programs real-time, but are still tending to consume other types of media content on their TVs. Many consumers choose bigger and higher quality TVs in order to enjoy more immersive watching experiences. Today, TVs are more than just viewing screens. TVs have seen their uses expanded into the fields of workout, productivity, entertainment and home Internet of Things (IoT). Samsung’s Smart TVs are becoming an integral part of their users’ daily lives, displaying the product’s boundless potential as a platform.
       
       
      Q. The 2018 Samsung Smart TV was presented as a device capable of supporting various activities, while the 2019 Samsung Smart TV was defined as a provider of customized services for any and all user preferences. How would you define the 2020 Samsung Smart TV?
       
      The 2020 Samsung Smart TV prioritizes delivering a next-generation screen experience to users. This year’s Samsung Smart TV enables users to harness new services, a range of partner applications and Samsung TV Plus in order to bring the content they want right in front of them easily and quickly. What defines the 2020 Samsung Smart TV is the facilitation of services like Bixby, Alexa and Google Assistant for easy access to such areas as art, fitness and gaming features across such applications as Samsung Health and Art Store.
       

       
       
      Q. Can you share one useful tip for Samsung Smart TV users?
       
      I prefer to pick the content I want to watch and enjoy it whenever I find it convenient to. I make good use of both Korean and international OTT services, as well as Samsung TV Plus, from Friday night through to the following morning and have developed my own TV guide packed full of exactly the content I want to enjoy. While streaming, I am also able to get my laundry done, as my Smart TV will let me know when my machine’s cycle is complete so that I don’t forget to take my laundry out of the machine.
       
      I also want to recommend the Art Store of The Frame, one of Samsung’s lifestyle TVs, as this lets you curate artworks that not only match your tastes, but also your mood or even the weather – a small luxury I very much appreciate in my home.
       
       
      Q. With the advancement of technologies, things we have previously only imagined are increasingly becoming a reality. Would you share how you think the Samsung Smart TV will evolve in the long term?
       
      The Smart TV I dream of is one with a constraint-free experience, whatever and whenever you want to do. This means a literally seamless experience when watching, playing or working with screens, controlling your devices and connecting to the world, for each and every consumer, regardless of their situation. I believe that this is the beauty of the technologies and innovations that Samsung can do better than any other.
       

      View the full article
    • By STF News
      There was a time when picture and sound quality and design were the main factors in determining the quality of a TV. Then came the inception of smart TVs – televisions equipped with operating systems just like computers or smart phones. The rise of this new technology allowed for the use of a broad range of applications on users’ TVs, while also providing more access to different kinds of content and facilitating connectivity with a wider range of devices.
       

      * Service availability may vary by region, service provider, language.
       
      Samsung has ranked number one in the global TV market for 14 consecutive years due to the ultra-high definition picture quality, immersive sound and rich user experiences provided by its televisions. And at the heart of it all has been Tizen OS, an open-source operating system that makes it easy for users to enjoy an expansive range of services quickly and conveniently.
       
      Samsung Newsroom looked into the key features offered by Tizen that are driving premium TV usability and elevating the experiences of both users and partners.
       
       
      User Experience – Access Vast Amounts of Content Easily
      When you use a smart TV powered by Tizen, most forms of content are just a few clicks away. Smart TVs equipped with the Tizen OS support major OTT (Over the Top) services applications by default. When hooked up, the TVs also provide access to Samsung TV Plus, which lets you view a range of content including variety shows, TV series and movies free of charge. This experience is further enhanced by the ‘Universal Guide’ feature, which harnesses the power of AI to make intelligent, personalized recommendations that are tailored to your preferences.
       

      * Universal Guide screen displayed above is available for European users only.
       
      With Tizen, quickly selecting the videos you want to watch from among the flood of content becomes a breeze. The operating system spares users from frustration by minimizing input lag, which is the time required for the TV to reflect commands. Tizen-empowered smart TVs also feature Auto Game Mode, which allows the TV to detect and automatically change settings for an optimal gameplay experience when the user is using a gaming console.
       
       
      Content Developer Experience – Streamlined Content Supply Across Devices
      To best enrich the smart TV experience, collaboration with a host of partners and developers is crucial.
       

       
      At Samsung Developer Conference 2019, Samsung Electronics unveiled a range of development tools that streamline the app building experience for the Tizen OS. ‘EasyST’ enables users to quickly test online video content on TVs, while ‘Wits’ helps with monitoring apps in development in real-time on a television. These and a range of other tools are available for anyone to access.
       
      What’s more, through use of ‘Samsung Checkout on TV’ users can easily subscribe to an app or purchase content using just their Samsung Smart TV, regardless of which kind of IPTV connection they have. This removes the need for the establishment of an independent payment system by developers.
       

       
      This platform also enables partners of Samsung Electronics to conveniently provide content to more than 140 million users in 197 different countries around the world. Since Tizen OS supports a broad host of TV models that range from FHD to QLED 8K, the operating system has made reaching a wider user base easier and more efficient. Tizen OS also offers support for a number of virtual assistants, including Bixby, Alexa and Google Assistant, which further facilitate easy access to a diverse array of content.
       

      * Service availability may vary by region, service provider, language.
       
      Across a vast range of locations and user types, Tizen connects users with development partners in order to expand the depth and scope of TV experiences. Going forward, the multi-faceted operating system will strike partnerships in areas such as arts, fitness and games in order to continue expanding the role that our televisions play in our lives.
      View the full article
    • By STF News
      We can’t guarantee our users have a good internet connection but we can still be helpful when they don’t.
      In ideal conditions the user will always maintain a good connection to the web but things are seldom ideal. Fortunately since we’re been building a web app we have a service worker which has the capability of caching network responses.
      If the network fails or takes too long to respond we can then use these cached responses to show the user the page they were looking for, letting people continue to use the app despite not being connected. Unfortunately our cache isn’t always perfect. Sometimes the user will be trying to go to a page which hasn’t been cached yet.
      If we haven’t anticipated this we may see the dreaded no connection message:

      Fortunately we are very smart developers [citation needed] and can show a branded offline page. So the user still feels like they are using our web app when the connection is lost. here are some examples:

      These are great for maintaining a consistent user experience during network failures which is the expected behaviour of a native app.
      These pages can do even more though, they can be used to provide entertainment such as The Guardian’s developer blog providing a crossword on their offline page. Which unfortunately I can’t find a live version of any more.
      The Guardian’s crossword offline page.
      A useful offline page for almost any Web App
      I’m going to propose, and build, a feature which should be useful to many apps and websites and would make your app still partly usable whilst your offline. This is to show a lit of relevant cached pages to the user:

      This example app is an RSS Feed reader. Where the user can read an RSS feed at a URL like so:
      /feed/?url=https://ada.is/feed This app is rendered on the server so it returns all the information in the HTML page, these pages get cached by the service worker. If your app uses JSON to populate pages on the client side this technique still works as long as you cache both the JSON responses and the pages which show them.
      This is a common pattern in many Web Apps and will work as long as you have pages cached.
      Step 1. Be prepared, by pre-caching the offline page
      Firstly we need to store the offline page, when the app starts. To do this I had the HTML file /offline/ and it’s resources /offline.js cached as soon as the app starts, by populating the cache during the service worker’s install event.
      const CACHE_NAME = "DENORSS-v1.0.0"; self.addEventListener("install", (event) => { event.waitUntil( caches .open(CACHE_NAME) .then((cache) => cache.addAll(["/", "/offline/", "/offline.js"]) ) .then(self.skipWaiting()) ); }); Step 2. Show the offline page
      Then when the user tries to navigate to a page we do not have we can show that cached /offline/ page.
      Our existing code first tried to respond with a live page, if that failed it would try retrieving the page from cache, if that fails instead of just failing and showing the browser error message we instead respond with the offline page.
      // Try showing the offline page if it's a navigation if (event.request.mode === "navigate") { const offlinePage = await caches.match("/offline/"); if (offlinePage) return offlinePage; } Step 3. Getting a list of cached pages
      This now shows the offline page when there is no alternative. Now lets provide a list of cached pages the user might like to read instead. Like in the example below.

      The first step we need to do is to open the web apps caches to find pages we want to access:
      const cacheKeys = await window.caches.keys(); const caches = await Promise.all( cacheKeys.map((cacheName) => window.caches.open(cacheName)) ); This gives us an array of caches.
      Next we want to find all of the cached pages from those caches, this works by using cache.matchAll with ignoreSearch: true to find all cache results from the /feed/ endpoint.
      const results = await Promise.all( caches.map((cache) => cache.matchAll("/feed/", { ignoreSearch: true, }) ) ); I only looked at the /feed/ end point because I felt that pages like /search/ with search results or the error pages like /404.html would not be useful to users and main pages like the home page / are already linked to in the navigation bar.
      Our results returns an array of arrays for the results from each cache. We will flatten this and then handle each cached response:
      results.flat().forEach(async (response) => { // Code goes here }); We only want to get the useful pages to the users so we will look at the query parameters to find only the pages are interesting. For our example they are requesting an RSS feed via the url parameter.
      const params = new URLSearchParams(new URL(response.url).search); const urlParam = params.get('url'); if (!urlParam) return; If there is no url query parameter, it’s not interesting so we won’t show it.
      Step 4. Rendering the list
      We have the URLs of the pages now and the raw query parameters but that won’t look very good for users. We can get some better labels to show to users by looking at the cached content itself.
      To get the data out of the response we need to get the text of the response:
      const dataAsString = await response.text(); If your data is stored as JSON then a JSON.parse should be enough to retrieve any interesting information such as a good page title.
      const data = JSON.parse(dataAsString); const title = data.title; For our example website, since it is server side rendered it uses HTML so I will parse the HTML instead, fortunately web browsers are good at HTML parsing. We will turn our raw text into a document fragment which can be queried using the usual DOM methods.
      In this example we read the text in the <title> tag. Other good elements to query would be <h1> or <h2> to get the first header in the document.
      const html = document .createRange() .createContextualFragment(dataAsString); const title = html .querySelector("title") .textContent.trim(); We use this title and the response URL to generate a link we can append to the list element to make a list of pages.
      el.insertAdjacentHTML( "beforeend", `<li><a href="${response.url}">${title}</a></li>` ); Here is a gif of it working, this was recorded with Chrome emulating an offline network connection:

      Thanks for reading and hope this helps.
      View the full blog at its source
    • By STF News
      We can’t guarantee our users have a good internet connection but we can still be helpful when they don’t.
      In ideal conditions the user will always maintain a good connection to the web but things are seldom ideal. Fortunately since we’re been building a web app we have a service worker which has the capability of caching network responses.
      If the network fails or takes too long to respond we can then use these cached responses to show the user the page they were looking for, letting people continue to use the app despite not being connected. Unfortunately our cache isn’t always perfect. Sometimes the user will be trying to go to a page which hasn’t been cached yet.
      If we haven’t anticipated this we may see the dreaded no connection message:

      Fortunately we are very smart developers [citation needed] and can show a branded offline page. So the user still feels like they are using our web app when the connection is lost. here are some examples:

      These are great for maintaining a consistent user experience during network failures which is the expected behaviour of a native app.
      These pages can do even more though, they can be used to provide entertainment such as The Guardian’s developer blog providing a crossword on their offline page. Which unfortunately I can’t find a live version of any more.
      The Guardian’s crossword offline page.
      A useful offline page for almost any Web App
      I’m going to propose, and build, a feature which should be useful to many apps and websites and would make your app still partly usable whilst your offline. This is to show a lit of relevant cached pages to the user:

      This example app is an RSS Feed reader. Where the user can read an RSS feed at a URL like so:
      /feed/?url=https://ada.is/feed This app is rendered on the server so it returns all the information in the HTML page, these pages get cached by the service worker. If your app uses JSON to populate pages on the client side this technique still works as long as you cache both the JSON responses and the pages which show them.
      This is a common pattern in many Web Apps and will work as long as you have pages cached.
      Step 1. Be prepared, by pre-caching the offline page
      Firstly we need to store the offline page, when the app starts. To do this I had the HTML file /offline/ and it’s resources /offline.js cached as soon as the app starts, by populating the cache during the service worker’s install event.
      const CACHE_NAME = "DENORSS-v1.0.0"; self.addEventListener("install", (event) => { event.waitUntil( caches .open(CACHE_NAME) .then((cache) => cache.addAll(["/", "/offline/", "/offline.js"]) ) .then(self.skipWaiting()) ); }); Step 2. Show the offline page
      Then when the user tries to navigate to a page we do not have we can show that cached /offline/ page.
      Our existing code first tried to respond with a live page, if that failed it would try retrieving the page from cache, if that fails instead of just failing and showing the browser error message we instead respond with the offline page.
      // Try showing the offline page if it's a navigation if (event.request.mode === "navigate") { const offlinePage = await caches.match("/offline/"); if (offlinePage) return offlinePage; } Step 3. Getting a list of cached pages
      This now shows the offline page when there is no alternative. Now lets provide a list of cached pages the user might like to read instead. Like in the example below.

      The first step we need to do is to open the web apps caches to find pages we want to access:
      const cacheKeys = await window.caches.keys(); const caches = await Promise.all( cacheKeys.map((cacheName) => window.caches.open(cacheName)) ); This gives us an array of caches.
      Next we want to find all of the cached pages from those caches, this works by using cache.matchAll with ignoreSearch: true to find all cache results from the /feed/ endpoint.
      const results = await Promise.all( caches.map((cache) => cache.matchAll("/feed/", { ignoreSearch: true, }) ) ); I only looked at the /feed/ end point because I felt that pages like /search/ with search results or the error pages like /404.html would not be useful to users and main pages like the home page / are already linked to in the navigation bar.
      Our results returns an array of arrays for the results from each cache. We will flatten this and then handle each cached response:
      results.flat().forEach(async (response) => { // Code goes here }); We only want to get the useful pages to the users so we will look at the query parameters to find only the pages are interesting. For our example they are requesting an RSS feed via the url parameter.
      const params = new URLSearchParams(new URL(response.url).search); const urlParam = params.get('url'); if (!urlParam) return; If there is no url query parameter, it’s not interesting so we won’t show it.
      Step 4. Rendering the list
      We have the URLs of the pages now and the raw query parameters but that won’t look very good for users. We can get some better labels to show to users by looking at the cached content itself.
      To get the data out of the response we need to get the text of the response:
      const dataAsString = await response.text(); If your data is stored as JSON then a JSON.parse should be enough to retrieve any interesting information such as a good page title.
      const data = JSON.parse(dataAsString); const title = data.title; For our example website, since it is server side rendered it uses HTML so I will parse the HTML instead, fortunately web browsers are good at HTML parsing. We will turn our raw text into a document fragment which can be queried using the usual DOM methods.
      In this example we read the text in the <title> tag. Other good elements to query would be <h1> or <h2> to get the first header in the document.
      const html = document .createRange() .createContextualFragment(dataAsString); const title = html .querySelector("title") .textContent.trim(); We use this title and the response URL to generate a link we can append to the list element to make a list of pages.
      el.insertAdjacentHTML( "beforeend", `<li><a href="${response.url}">${title}</a></li>` ); Here is a gif of it working, this was recorded with Chrome emulating an offline network connection:

      Thanks for reading and hope this helps.
      View the full blog at its source


×
×
  • Create New...