Tips for building fast and light Vue.js SPA components

Tips for building fast and light Vue.js SPA components

Tips for building fast and light Vue.js SPA components. Building Single Page Apps is quite common these days. Frontend frameworks come with tools and boilerplates that scaffold starter projects which are most of the time Single Page apps.

However, as your application evolves, you add more features and more pages, and consequentially your SPA becomes harder to manage. The application starts to load slower, the javascript of your app is parsed slower by the browsers and you may start questioning whether SPA was the right decision or not.

There are 3 main aspects when we talk about the performance of a Single Page app:

Code Performance

This is most of the times correlated with what your application does and how intense some of the tasks might be for a browser or device. Some apps might not care too much about code performance because they might only retrieve and display data, while others might have some processing or complex visuals that have a high impact on the performance. Code performance can be most of the times improved by the developers who build the application unless they rely on some packages that cause performance issues.

Perceived Performance

This aspect is correlated to how users perceive the performance of a website. Perceived performance is often associated with "how fast a website feels when it loads" rather than how fast it loads and these 2 things can be quite different. While the website can load very quickly, it is important that it feels smooth and fast. For example, loading images progressively even if this process is slower  might be perceived as smoother and faster compared to having content jumping around or displaying spinners.

Code Size

Code size has an impact on performance. The more code you load, the slower your website loads and this is especially true for javascript. An interesting read on this topic is The Cost of Javascript which has a very good comparison between loading an image and some javascript of the same size. While those 2 download in the same amount of the time, the Javascript takes 3.5 more seconds to parse, compile and execute on a low end mobile device compared to the image. Perhaps, code size is one of the main factors that affects overall performance of a SPA simply because code size can grow very fast in a SPA without noticing.

Improving Performance of a Vue.js SPA

Vue.js is great, no doubt about it. The framework itself is light and performant compared to other alternatives, however this doesn't mean it will build you a performant SPA out of the box.

So here are some tips and tricks to improve performance for each of those categories listed above:

Code Performance

Avoid complex logic based on watch, computedupdate or beforeUpdate hooks

Having complex logic around these Vue.js blocks might end up with triggering extra component re-renders or render loops that can affect the end performance of your code.

Some common examples that can affect performance are:

- Setting data inside computed

  • Emitting/setting multiple data properties inside watchers that might end up triggering that watcher again

  • Setting data inside beforeUpdate hooks that might end up with re-rendering the component

  • Mutating object/array props directly

Try to avoid these and rely on simpler and cleaner ways such as:

  • Transforming your data in your upper component before passing it down so the child doesn't have to rely on watchers

  • Emitting events to notify parent components rather than mutating props if it's easier

  • Replacing computed with watcher in case you need to set data when another piece of data changes

**Measure code performance with Chrome Dev tools. You can find a good guide on how to do that here **

Try to isolate certain areas of your application that feel slow and see if there is any bottleneck on the code side that slows stuff down.

Test on a low end device or with a CPU slowdown in chrome dev tools

If your app runs well with a CPU slowdown it will run even better on a desktop or laptop. We often develop on high end machines and most of the times and everything feels smooth and fast but this is not the case when testing on a cheap smartphone.

Use Vuex with caution

There is a tendency to overuse vuex and put every api call in it. While this might be a little bit helpful, try using vuex only and only when you need it. The answer to putting something into Vuex can be based on this:

Do I need this piece of data in more than 2 non child-parent components ? Yes -> store in vuex. No -> Use local component data.

This is important because storing everything in Vuex creates an extra layer of complexity and sometimes may lead to certain performance issues like having big chunks of data in the store that are not relevant for many portions of the app.

Avoid shady third parties

Although this sounds very generalized, try to not use many third parties especially if they have a small scope. An interesting read on this topic is this article by David Gilbertson who says that small third parties introduce a lot of cost from learning curve to maintenance cost which in the end is the same or even more as creating your own solution. If you need a small component or piece of code, take the time to make it yourself. This will give you more control to fine tune it and maybe avoid performance issues from third parties which can be hard to tackle.

Perceived Performance

Use GPU based transitions and animations

What does this exactly mean ? Well, try to avoid any transitions or animations which are not based on these properties:

  • Position — transform: translateX(n) translateY(n) translateZ_(n_);
  • Scale — transform: scale(n);
  • Rotation — transform: rotate(_n_deg);
  • Opacity — opacity: n;

These css properties are very well optimized for all devices and will ensure smooth GPU based animations. This is especially important for mobile devices which, if don't use animations based on these properties might make your website feel janky and slow.

Load content beforehand

If one of your pages needs to display a lot of content based on some data, you can try using beforeRouteEnter hook to retrieve your data. Consider this example:

Retrieving data in mounted hook:

Retrieving data in beforeRouteEnter hook:

Although first example is renders faster, it is not perceived as smooth as the second. Second example loads the page along with content rather than displaying the content later when data is received from the api. Here's a comparison of the code for these 2 cases:

Fetch data in mounted/created hook

function getData() {
  return butter.post.list({ page: 1, page_size: 10 });
}

export default {
 data() {
  return { 
   blogPosts: []
  }
 }
 async mounted() {
   let res = await getData();
   this.blogPosts = res.data;
 }
}

Fetch data in **beforeRouteEnter **hook:

function getData() {
  return butter.post.list({ page: 1, page_size: 10 });
}

export default {
 data() {
  return { 
   blogPosts: []
  }
 }
 async beforeRouteEnter(to, from, next) {
   let res = await getData();
   next(vm => {
    vm.blogPosts = res.data;
   });
 }
}

You can see that the difference is not that big. The second option might feel a bit more verbose but it has a different visual impact.

Lazy load images

If your page contains a lot of images, it might be a good idea to lazy load them and display them with the help of api's such as IntersectionObserver.

Here's a quick way on how you could do that:

npm install vue-lazyload

import Vue from "vue";
import VueLazyload from "vue-lazyload";

Vue.use(VueLazyload);

Now for images, instead of **src attribute **for images use the **v-lazy **directive:

Don't use very long transitions and animations

Usually short animations feel snappier and faster. Having a really long animation is not worth it unless it's a complex one that changes while being displayed (e.g loading animation)

Google Material Design  suggests ranges between 200ms and **300ms **This duration usually feels the best for animating dropdowns, menus, appearing content, page transitions and so on.

Also try not to overuse animations. People in the Vue.js community overuse **transition **and transition-groupcomponents because they are simple to use and you get excited about it but most of the time displaying a simple list without animations has better perceived performance especially if you're on mobile and you see like 1 or 2 list items.

Code Size

Finally we get to our final topic. This one has many small tips that can have a big impact.

Consider small third party libraries or no libraries at all

For example moment.js can be replaced with date-fns which much smaller and tree shakeable.

Moment: you either import it all or nothing                          **Date-fns: **You can import only certain functions. The whole packages is 10 times smaller than moment.

 

I'd recommend Bundle Phobia which is a good resource to quickly measure how much a package weights. 
If you need a simple functionality, you can even consider making it yourself which would be smaller than importing a package that does 10 other extra things besides your needed functionality.

Use dynamic imports for routes

Using dynamic imports will make sure that the code for each page is loaded only when the user navigates to a certain page. It will also make sure that the initial code loaded when users first visit your website, will be smaller because it will contain only core packages used everywhere in the app.

Here's how you can do it. Instead of this:

import Profile from '@/views/Profile';

Consider this:

const Profile = () => import('@/views/Profile');

If you're question why you should split a route that has let's say **3kb **then you could make use of webpack chunk names to group more routes into a single file that is downloaded when users navigate to any of the routes placed in this chunk. Here's an example:

const ClientDetails = () => import(/* webpackChunkName: "clients" */ 'src/views/admin/clients/ClientDetails');

const ClientList = () => import(/* webpackChunkName: "clients" */ 'src/views/admin/clients/ClientList');

Now we can say that we have a good reason to split these 2 pages into a separate chunk because they might have a bigger size. Another benefit of doing this is that certain packages that are used only in this pages will be bundled along with them without polluting the main vendor file.

Try doing this for **ALL **your routes. Yes, that's right for all routes. This will result in a good performance boost.
One caveat when you do this will be that you might notice a slight delay when clicking on certain pages especially when you are on a slower connection. You can solve this UX issue by displaying a top progress similar yo how Youtube does it for example

Here's the code to do it:

npm install nprogress

Create a **progressbar.js **file and place this code

import NProgress from 'nprogress';
const progressShowDelay = 100;
let routeResolved = false;
/**
 * Initializes NProgress after a specified delay only if the route was not resolved yet.
 */

export function cancelTopProgress() {
  routeResolved = true;
  NProgress.done();
}
function tryInitProgress() {
  routeResolved = false;
  setTimeout(()=> {
    if (!routeResolved) {
      NProgress.start();
    }
  }, progressShowDelay);
}
export default function initProgress(router) {
  router.afterEach(cancelTopProgress);
  router.beforeEach((to, from, next) => {
    tryInitProgress();
    return next();
  });
}

In your main.js or where you create your router, call initProgress with the vue router instance:

initProgress(router);

You'd also need some extra css which you can find here

Use only the packages you need

It's always tempting to add a new fancy package that does some cool stuff. Always take into consideration that this might affect your end app size.
For example if you build a custom solution, you might not need any css framework like Bootstrap, Bulma and so on. It's fairly trivial to create a grid or even create custom components for that. Even if it's more work, it will pay off in the end. For example, on a project we worked on fairly recently we were able to reduce the total loaded css from 150kb gzipped which was containing Bootstrap and some other stuff to only 20kb gzip by creating custom components for grid, layout cards and so on. A good inspiration can be the Element UI layout components which are open source. You can build your own layout components (row, col) which in the end can cover like 80% of your Bootstrap needs.

Optimize early and often

Try to optimize, enforce rules regarding packages and code size as early in the project as possible. Do it often. Make sure you check from time to time that these rules are respected and followed. This will ensure a small and performant app. Doing size optimizations at the end of the development phase can be very hard, can introduce a lot of bugs and it's more likely for you to give up just because you'd think it would take too much time.

Measure size

You can always check and enforce limits for your bundle size. If you use Vue CLI 3, it will output the size for each module. Make sure you always check it and fight with it so it doesn't go up. Above that, you can use tools like Lighthouse which is available in Chrome Devtools to measure size & performance. It will give you nice tips & hints on what you can improve.

Conclusion

I really hope that some of these tips, although general can help you build faster and lighter SPA Vue.js apps. These are only some of the best practices and tips to make an application small and performant. There are many more web related aspects which we didn't cover like images, cache and more yet those can be discussed in a separate topic as they are not related to Vue so much and are general best practices for the web. Hope you enjoyed this article and found it useful. Feel free to leave a suggestion or comment below.

Recommended Reading

Laravel and Vue.js: Why Is This Couple Getting Popular?

How to use Vue.js in a PHP your application

Working With Vuetify Forms and Validation

How to Integrate the Authentication Module to Nuxt application

Why Is Nuxt.js the Best Choice for Your Next Web Application?

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

What’s new in HTML6

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

What are the differences between the various JavaScript frameworks? E.g. Vue.js, Angular.js, React.js

What are the differences? Do they each have specific use contexts?

What are the differences? Do they each have specific use contexts?

Ember.js vs Vue.js - Which is JavaScript Framework Works Better for You

Ember.js vs Vue.js - Which is JavaScript Framework Works Better for You

In this article we will discuss full details and comparison of both Ember.js and Vue.js

JavaScript was initially created to work for web applications. But today they have become the favorite of mobile app developers. Most of the developers prefer to work with frameworks based on JavaScript. It simplifies coding. You can use JavaScript with almost any framework.

The use of a particular framework will decide how easy and fast it is to create the app. So, you must choose the best one suited for the app that you are planning to build. You must make a wise choice so that you benefit in the end. Among the crowded market, two of the frameworks stand out. We will make a comparison between Ember.js and Vue.js.

Why Do You Select A Particular Framework?

Before we start comparing the two frameworks, we should understand the factors that lead to the choice of a framework. Each developer chooses a framework before he or she goes to work on an app. Let us see the reasons for the selection.

● The codes must be easy to understand and transparent.

● The framework should give the maximum power with the least amount of coding.

● The framework should provide a well laid out structure to work on.

● Does the framework support an in-built router or an external plug-in router?

● The framework should be able to transfer more data on a full page-load so that it becomes a single-page app. A single-page app is more beneficial for the application.

● In single page architectures if there is a need for users to share links to sub-screens within the interface, then the framework should have the capacity to route based on the URL.

● A tighter template option can help in enabling two-way binding.

● The framework should not conflict any third-party library.

● Testing the codes inside the framework should be easy.

● The framework should provide the HTTP client service for AJAX calls

● The documentation is essential. It should be complete and up-to-date.

● The framework should be compatible with the latest version of the browser.

● The framework has to fulfill the above conditions for easy construction of the app. You must ensure that the framework you choose meets the conditions.

Vue.js Explained

Developers are always looking at new frameworks to build their apps. The main requirements are speed and low cost. The framework should be easy to use by even new developers. You should be able to use it at low cost. Other considerations are about simple coding, proper documentation, etc.

Vue.js combines a lot of good when it comes to software language for web app development. The architecture of Vue.js is easy to put in use. The apps developed using Vue.js are easy to integrate with new apps.

Vue.js is a very lightweight framework. It makes it fast to download. It is also much faster than other frameworks. The single-file component nature of the framework is also beneficial. The size has made it very popular.

You can further decrease weight. With Vue.js you can separate the template-to-virtual DOM and compiler. You can only deploy the minified and zipped interpreter which is only 12 KB. You can compile the templates in your machine.

Another significant advantage of Vue.js is that it can integrate easily with existing applications created with JavaScript. It will make it easy for using this framework to make changes to applications already present.

Vue.js also integrates easily with other front-end libraries. You can plug in another library and make up for any deficiency in this framework. This feature makes this tool a versatile one.

Vue.js uses the method of rendering on the streaming-side server. You can render your component and get a readable stream. You can then send this to the HTTP server. It makes the server highly responsive. Your users will get the rendered content very quickly.

Vue.js is very SEO friendly. As the framework supports server-side rendering, the views are rendered directly on the server. The search engines list these.

But the most important thing for you is the ease with which you can learn Vue.js. The structure is elementary. Even new developers will find it easy to use it to build their apps. This framework helps in developing both small and large templates. It helps to save a lot of time.

You can go back and check your errors very easily. You can travel back and inspect all the states apart from testing your components. It is another important feature as far as any developer is concerned.

Vue.js also has very detailed documentation. It helps in writing your applications very quickly. You can build a web page or app with the basic knowledge of HTML or JavaScript.

● Vue.js has pure architecture. It helps in integration with other apps

● Vue.js is lightweight and fast. It can be made lighter by deploying only the interpreter

● You can separate the compiler and the template-to-virtual DOM.

● Due to smooth integration, you can use this to make changes to existing apps

● To make up for any shortfall, you can plug-in any library and makeup.

● As Vue.js uses streaming-side server rendering, your users can get quick responses.

● The server-side rendering also helps in being ranked higher by search engines.

● It has a simple structure. Easy to use for any new developer

● You can go back and check and correct your errors.

● You can check all the existing states.

● Detail documentation also helps build the web page or application very quickly.

Ember.js Decoded

Ember.js is an MVVM model framework. It is open-source software. This platform is mostly used for creating complex multi-page applications. It maintains up-to-date features without discarding any of the old features.

With this framework, you have to follow the architecture of the framework strictly. The JS framework is very tightly organized. It reduces the flexibility that other frameworks might offer.

There is a very refined and developed control system for its platforms and tools. You can integrate it with the new version with the tools provided. There is strict guidance about avoiding outdated APIs.

You can understand Ember’s APIs easily. They are also easy to work. You can make use of highly complex functionalities simply and straightforwardly.

The performance is better as similar jobs are processed together. It creates batches of similar bindings and DOM updates to improve the performance. It means that the browser needs to process them in one go. It will avoid recomputing for each task, wasting a lot of time.

You can write the codes in a simple manner and modules. You can use any of Ember’s APIs. It is possible due to the presence of Promises everywhere.

Ember comes with a well-written guide. The API is recorded in a useful manner. It is a front-end framework that is loaded. Ember has a router, pipeline, services, etc. of its own.

The basis for views, controllers, models, and framework is the Ember Object Model. All components come from the same objects. The framework is firm and steady. The reason is that all elements have similar jobs and characteristics.

Ember has made the general application, organization, and structure clear so that you don’t make any mistakes. You will have no chance to complicate the application unnecessarily. If you have to go out of the defined limits, you will have to force your way out.

The language used for templating in Embers is Handlebars. This language helps Embers to keep its logic out of view. The clean syntax of Handlebars makes it easy for you to read and understand the templates. Handlebar templates are faster to load.

Another advantage you gain from Handlebar is that you don’t have to update your template every time you add or remove data from the page. It will be done automatically by the language itself.

A community that is continually improving the framework supports Ember. They are updating the framework with the latest technology. They also make sure that backward compatibility is possible.

● Ember.js is an open-source MVVM model framework suitable for complex multiple-page applications.

● It offers both the latest and old features.

● It has a very tightly structured framework which doesn’t offer much flexibility

● A very refined control system helps you to integrate with new versions without any problem.

● There is strict guidance about avoiding outdated API versions.

● Ember’s APIs help you to use complex functionalities in a simple manner

● There is no recomputing for each task as the framework allows the browser to do similar functions together.

● Promises allow you to write modular and straightforward code using any API of Ember.js.

● Ember.js is a fully loaded, front-end framework.

● The framework is stable because all components have the same functionalities and properties.

● It has well-defined limitations which will prevent your complicating your application

● Handlebars, the language used by Ember.js allows you to read and understand templates easily. It also helps to load the templates faster.

● Handlebars will ensure to update the template every time you add or remove data.

● Ember.js has an active community that updates the framework regularly and facilitates backward compatibility.

A Comparison Between Ember.js And Vue.js

This article intends to compare the features of both frameworks. Let us see how the characteristics of these frameworks compare. It will help you to make use of the right framework for your web application.

When you need a modern engine for an old application, it is Vue.js which will help you. It combines the best properties of other frameworks. Vue.js is a developing framework. A ready-to-use library of interface elements does not exist. However, many third-party libraries can help you.

Ember.js offers you a well-organized and trustworthy framework. When the development team is big, this is the framework that suits best. It allows everyone to understand the written code and contribute to a common project. The technology will be up-to-date, and the platform will be stable.

Vue.js can help you use the syntax of different kinds. It helps in writing the codes with ease. It is also an SEO friendly framework. Ember is a fully loaded front-end framework and can help you develop the applications very fast. But it is not suitable for developing small projects.

It is not easy to say this is better than that. It will depend on what kind of project you have undertaken. Both have their pluses and minuses. The below table will help in a better comparison.

Final Thoughts

It is not easy to conclude as to which is better. It all depends on the application that you want to develop. Both frameworks are developing. Both are getting updates. Both the communities are working on the frameworks.

While Vue.js is more comfortable for writing codes, Ember is a full-stack framework allowing the development of apps very fast. It is suitable for big projects. It is too complicated to be used for smaller projects.

We hope you had a great time reading this article. If you’ve any questions or suggestions related to this blog, then feel free to ask them in the comment section. Thank You.!