Published on December 1, 2022

7 Tips For Creating Mobile-Friendly JS Sites

7 Best Practices For Creating Mobile-Friendly JavaScript Sites

Nowadays, mobile traffic accounts for 58.99% of the global online traffic, making it a must to create websites as mobile-friendly as possible. 

In fact, this adoption has even changed the way we think about our sites and applications:

  • Search engines like Google are now implementing mobile-first indexation, crawling and ranking your pages predominantly from the mobile version
  • Software companies, embracing this shift in user behavior, are focusing more and more on implementing progressive web applications (PWAs) to create a seamless experience between desktop and mobile.
  • The eCommerce industry has seen massive growth over the past years, hitting “$359.32 billion [in sales] in 2021, an increase of 15.2% over 2020.”

To make a website mobile-friendly, there are two main objectives: responsive and fast.

Mobile devices, because of their nature, don’t always count with the best connection or fast CPUs, making it a real challenge for these devices to handle JavaScript as efficiently as desktops.

Example of mobile vs. desktop boot-up time

Image source: HTTP Archive

In today’s article, we’ll take a look at some of the best practices to keep top of mind when optimizing your JavaScript sites for mobile devices.

1. Adopt a Mobile Mindset and Set a Performance Budget

Creating a mobile-friendly website comes with a few constraints of its own, so you’ll need to use a different approach if you want to take the full advantage of the format.

To adopt a mobile mindset, there are two things that are required:

  • Create a clear process of collaboration between the design and development teams
  • Set a performance budget and adhere to it

To make a website as responsive and fast as possible, it’s necessary that the design and development team can agree on designs from the beginning. Allowing developers to request changes to reduce page size, for example.

Also, it’s important that your team has a clear goal in mind while developing the site. For example, the total number of requests allowed per page or the final file size for each page.

A good place to start with this is setting a goal of, for example, 500 KB per page. This restriction will influence a lot of choices, like the number of features implemented and how much JavaScript is allowed per page.

Setting a performance budget is not just useful to avoid creating slow sites that will take longer to optimize, but it will also help your team make decisions faster.

2. Use the Async or Defer Attributes

For users to see your website, the browser will need to fetch all necessary files, download them and then use them to build (or render) the site. This process will take more or less time depending on several factors like the device, network connection, server response time, etc.

However, JavaScript files have a significant impact on the performance of the website because it needs to be downloaded and executed before the rest of the content can be parsed, creating a bottleneck in the rendering process.

Example of the process that happens when a browser detects a file.

Image source: FlaviCopes

As seen in the image above, once the browser detects the file, it’ll stop all other processes and deal with the JavaScript file. In the meantime, the user is left waiting without being able to interact with the page.

To combat this, it’s been a common practice to add the <script src=”script.js”></script> line before the closing </body> tag, so the browser would parse the entire body before encountering the JS file.

However, today we can use Async and Defer to avoid parser-blocking JavaScript issues.

These are used as attributes for the script element. When both are present, the Async attribute will take precedence over the Defer attribute – which will act as a fallback.

When we use the Async attribute, we’re basically telling the browser to download the JavaScript file in parallel to the HTML parsing, only pausing the rendering process to execute the JS once the resource is available.

What it looks like when we tell the browser to download JavaScript

Image source: FlaviCopes

This is a great method to shorten the time to first paint, providing a better user experience than a blank page. However, there’s something important to factor in here: Async scripts don’t wait for anything, and nothing waits for them.

An Async script is as independent as it gets, so they don’t need to be executed in order. If script A is first in line than script B, but script B downloads first, then script B will be executed first.

Because of this, it’s better used for third-party scripts, like counters and ads, where the order isn’t relevant.

But what if order IS important? Then we can use the Defer attribute. This attribute has two main differences: 1) it’ll download the JavaScript files in parallel as Async but will wait until the HTML is completely ready before executing…

Browser downloading the JavaScript files in parallel as Async

Image source: FlavioCopes

… 2) it will respect the order of the scripts, so no matter which downloads first, script A will always be executed before script B – which can be very helpful if we need to load a JS library and then scripts depend on it.

Not blocking the main thread with JavaScript is a quick and very powerful way to improve site performance.

3. Minify and Compress Your JavaScript Files

Minifying your JavaScript file can help you save some precious bytes by deleting all unnecessary elements from your JavaScript code like whitespace, comments, using shorter names, etc., and a smaller file means less download time, speeding your site load speed.

JavaScript is written by and for humans, so it’s important for developers to use formatting and descriptive variable and function names to make sense of the codebase and be able to debug it later if needed.

On the other hand, machines don’t really need all this extra text, so even a stripdown JavaScript code can be interpreted well by the machine.

Tools like JavaScript Minifier and UglifyJS can help you minify your scripts.

As an example, here’s a simple JS script:

//This is a comment//This is another comment//Well… minify me thenfunction sayHello(name) { console.log(“Hi ” + name + “!”);} sayHello(“Reader”); 

Here’s the minified version:

function sayHello(l){console.log(“Hi “+l+”!”)}sayHello(“Reader”);

In addition to minifying your code, you can also enable Gzip compression to reduce file size by an extra 70% (in most cases).

Note: This is different from Obfuscation, which is used to turn code unreadable by humans in order to hide business logic. It could, in theory, reduce file size, but that’s not its main objective.

4. Use Code-Splitting

Although it won’t have any effect on your JS file size, splitting your code into functional modules that are called on-demand or parallel can have a huge impact on page performance.

Instead of having the browser download a huge JavaScript file with all the code, you can use a module bundler like Webpack and serve your JS in chunks or bundles – to use the correct name – freeing the client from having to download and execute pieces of code that won’t be using any time soon and letting the user interact with the page faster.

Here’s the complete code-splitting Webpack documentation for reference.

5. Remove Unused JavaScript Code

There are two main types of unused JS code:

  • Non-critical JavaScript – it’s not used at the top of the content (above the fold content) but can be used somewhere else on the page
  • Dead JavaScript – which is JS that’s not used anywhere on the page

This can happen because of many reasons like temporary test code, residual code from a previous version, etc. and can represent a real issue as the users’ browsers need to download, parse, compile and evaluate the code for no reason at all, wasting processing and network power.

Be mindful that this is a very common problem, even for big brands. In fact, if we use Page Speed to evaluate Nike’s homepage, here’s the result for mobile:

Example of Nike's Page Speed - Core Web Vitals

The two most critical suggestions from Google are “reduce unused JavaScript” and “eliminate render-blocking resources.”

Example of the need to reduce JavaScript to speed up site

But can we detect more accurately which scripts are not being used? Well, we can use the Coverage Tab from Chrome DevTools.

On the page, and with DevTools open, let’s open the Command Menu (Command+Shift+P for Mac and Control+Shift+P for Windows) and start typing coverage.

How to detect script not being used

From there, let’s click on the refresh button and wait for it to be populated.

Results shown when you "show coverage" on unused script

Once it’s ready, we’ll see this information on the Coverage tab. 

Collected coverage results on unused script

The Total Bytes column represents the full size of the file downloaded by the browser, while the Unused Bytes column is the total size of the code not being used by the page. In Nike’s case, 60% of the downloaded JavaScript is not being used from the first JS file, and it’s just consuming resources.

Deleting all this unnecessary data will create a smaller JS file and greatly increase the site’s mobile performance.

6. Prerender Your Pages for Search Engines

Users are not the only ones who’ll access your website through a mobile device. Google has set as default a mobile-first indexing process, so the site performance (speed, responsiveness, accessibility, etc.) will be evaluated starting with the mobile version.

Although following these best practices ensures a better-performing JavaScript site experience, several JavaScript SEO problems must be dealt with before Google can rank you higher in the search result pages. Most of them are related to rendering.

For a more in-depth explanation of the different ways to handle rendering, check our guide on server-side rendering vs. client-side rendering

However, regarding SEO gains, using Prerender can make your pages score higher on Google Page Speed Insights and solve most of the crawling, indexation, and rendering issues associated with JavaScript-heavy sites without complex and expensive workarounds.

To use Prerender, all you need to do is install our middleware, so it can detect when Googlebot (or any other search engine crawler) accesses your site, and it’ll send a request to our servers. Prender will then download all the necessary files, render your page and create a snapshot of it to serve as a static HTML to the search engine.

Although the first time it triggers this process can take a few seconds, Prerender will cache this snapshot and use it, from there on, every time a search engine requests the page. Turning JavaScript-heavy pages into instant responsive and fully rendered HTML.

Pro Tip: Use Mobile Prerendering

When users access your site from a mobile device, you want to serve them images with smaller file sizes, different layouts (like a different menu bar) to make navigation easier and data more suited for the vertical/small screen, and, in some cases, even slightly different content.

The same thing should be done for mobile web crawlers, especially for search engines like Google that care so much about the mobile experience. For large brands, getting high Page Speed scores on mobile is a tough task, requiring many workarounds and compromises.

However, for enterprises using Prerender, it is as simple as turning “mobile rendering” on in their account.



This will allow Prerender to create a different snapshot of your mobile website version and serve it to search engines when they access your site with a mobile user-agent.

7. Use Browser Caching

Now that we mentioned caching, there’s a way you can leverage the browser’s cache to speed up your site speed from the second visit onwards.

To do so, you’ll need to set an expiration date for your assets from the htaccess file:

## EXPIRES CACHING ##

<IfModule mod_expires.c>

ExpiresActive On

ExpiresByType image/jpg “access plus 1 year”

ExpiresByType image/jpeg “access plus 1 year”

ExpiresByType image/gif “access plus 1 year”

ExpiresByType image/png “access plus 1 year”

ExpiresByType text/css “access plus 1 month”

ExpiresByType application/pdf “access plus 1 month”

ExpiresByType text/x-javascript “access plus 1 month”

ExpiresByType application/x-shockwave-flash “access plus 1 month”

ExpiresByType image/x-icon “access plus 1 year”

ExpiresDefault “access plus 7 days”

</IfModule>

## EXPIRES CACHING ##

By doing so, you’re effectively telling the browser to keep those files in its cache until that time. Hence, the next time the user accesses your site, the browser won’t need to download them again. Instead, it can use the cache files to render the page, cutting the entire download waiting time.

Wrapping Up: Other Mobile Optimization Practices to Keep In Mind

So far, we’ve focused mainly on JavaScript optimization.

Still, many more factors influence the user experience on mobile.

Here are a few more considerations worth implementing:

Prioritize above-the-fold content

This is the first content that appears on the user’s device screen. Prioritizing all resources needed to render this section first can provide a better experience to users and will ensure a better score on Pagespeed Insights.

Optimize your images

Images significantly impact your page’s file size and, thus, your site’s speed. Make sure your team is using the correct practices:

  • For big images, try to hit 150 KB to 500 KB, and make sure to compress them with tools like ​​https://tinypng.com/
  • Don’t serve images larger than the screen can actually display; users won’t be able to appreciate them, and their phones will need more network bandwidth to deal with them
  • Change all PNG images to JPGs, or WebPs if possible, as these are 33% lighters than JPGs files
  • Lazy load your images to allow the page to become interactive faster and make the browser download visual assets only when their needed

Use Media Queries

Media queries are responsive CSS rules that allow you to control how your page renders based on the user device, creating a responsive experience across all screen sizes including mobile devices.

For example, you can use a media query to tell the browser to hide a specific element on the phone or to make the font size adapt to the screen, so it’s always easy to read the page’s content.

Here’s an example from W3bschool:

“If the browser window is 600px or smaller, the background color will be light blue:”

@media only screen and (max-width: 600px) {   body {     background-color: lightblue;   } }

Although this tutorial was focused on JavaScript sites, there are many other “general” best practices to help you build the best mobile-friendly site and application possible.

If you’d like to keep exploring a few more recommendations, here are 10 more tips to build a mobile-friendly website from scratch. These tips will help you make your site more responsive, faster, and SEO friendly.

And if you apply any of these suggestions, let us know how it went through Twitter.

We’re always excited to learn what you’ll build next!

Leo Rodriguez

Leo Rodriguez

Leo is a technical content writer based in Italy with over 4 years of experience in technical SEO. He’s currently working at saas.group as a content marketing manager. Contact him on LinkedIn.

Table of Contents

Prerender’s Newsletter

We’ll not send more than one email per week.

More From Our Blog

In this article, we'll explore practical tips to optimize your e-commerce site for mobile shoppers and convert them into loyal,
In this article, we will give more context on dynamic content and how to manage it with Prerender.

Increased Traffic and
Sales Awaits

Unlock missed opportunities and reach your full SEO potential. When more web pages are crawled, it’s easier to index more of your site and boost SEO performance. Get started with 1,000 URLs free.