Categories
Performance User Experience

Loading assets based on bandwidth

While dealing with custom CJK fonts in one of the application, I found that the font is taking too much time to load specially on a mobile connection. The reason was simple : the file size of the font even with the selected glyph were high enough to block the bandwidth. Sacrificing the custom font and using default system font was not an option UX designers were in favor off. 

These heavy fonts caused slower first contentful paint(FCP) and reducing the lighthouse score drastically for mobile users. This was not acceptable. For desktop users it was still ok to load, but if the. user has slower bandwidth, then the page would not come into action for few secs. So, loading font information after sometime was still a better choice even though it would case a minor flickering.

The only way was to make the custom font load after the page is ready if the user has good bandwidth and further delay the process if bandwidth is not good enough. The idea behind this approach is to delay loading of some assets that are relatively heavy and render more important items first.

// considering maximum mobile width as 700
const MAX_MOBILE_WIDTH = 700;

// Time taken to load any ajax, other images, javascript - hydration, analytics etc
const INTERACTION_READY_WAIT_TIME = 5000; 

let connection =  navigator.connection || navigator.mozConnection || navigator.webkitConnection;

const  isSlowNetwork = Boolean(connection && /(2g|3g)/i.test(connection.effectiveType));

if (isSlowNetwork && window.innerWidth < MAX_MOBILE_WIDTH) {  
    window.addEventListener('pageshow', function() {
        setTimeout(function() {      
            // do what you want to defer, load the heavy elements    
        }, INTERACTION_READY_WAIT_TIME);  
    });
} else {  
    // load the heavy elements,
}

Additionally, adding event listener on the page show event make sure that the loading should only happen after all the critical assets are loaded.

This process has few drawbacks at this moment of writing this article. Network speed detection api is still not available for few browsers, but that list is small and should get support incrementally. If your user base is more of chrome, edge and android specific, you may choose this hack to load content gracefully and improve the critical rendering of your application. 

Comments