Thursday, November 15, 2018

Dramatically Speed Up Your React Front-End App Using Lazy Loading

A constant challenge faced by front-end developers is the performance of our applications. How can we deliver a robust and full-featured application to our users without forcing them to wait an eternity for the page to load? The techniques used to speed up a website are so numerous that it can often be confusing to decide where to focus our energy when optimising for performance and speed.

Thankfully, the solution isn't as complicated as it sometimes might seem. In this post I'll breakdown one of the most effective techniques used by large web apps to speed up their user experience. I'll go over a package to facilitate this and ensure that we can deliver our app to users faster without them noticing that anything has changed.

What Does it Mean for a Website to be Fast?

The question of web performance is as deep as it is broad. For the sake of this post I'm going to try and define performance in the simplest terms: send as little as you can as fast as you can. Of course, this might be an oversimplification of the problem, but practically speaking, we can achieve dramatic speed improvements by simply sending less data for the user to download and sending that data fast.

For the purpose of this post I'm going to focus on the first part of this definition—sending the least possible amount of information to the user's browser. 

Invariably, the biggest offenders when it comes to slowing down our applications are images and JavaScript. In this post I'm going to show you how to deal with the problem of large application bundles and speed up our website in the process.

React Loadable

React Loadable is a package that allows us to lazy load our JavaScript only when it's required by the application. Of course, not all websites use React, but for the sake of brevity I'm going to focus on implementing React Loadable in a server-side rendered app built with Webpack. The final result will be multiple JavaScript files delivered to the user's browser automatically when that code is needed.

Using our definition from before, this simply means we send less to the user upfront so that data can be downloaded faster and our user will experience a more performant site.

1. Add React Loadable to Your Component

I'll take an example React component, MyComponent. I'll assume this component is made up of two files, MyComponent/MyComponent.jsx and MyComponent/index.js.

In these two files I define the React component exactly as I normally would in MyComponent.jsx. In index.js, I import the react component and re-export it—this time wrapped in the Loadable function. Using the ECMAScript import feature, I can indicate to Webpack that I expect this file to be dynamically loaded. This pattern allows me to easily lazy load any component I've already written. It also allows me to separate the logic between lazy-loading and rendering. That might sound complicated, but here's what this would look like in practice:

I can then import my component exactly as I normally would:

I've now introduced React Loadable into MyComponent. I can add more logic to this component later if I choose - this might include introducing a loading state or an error handler to the component. Thanks to Webpack, when we run our build, I'll now be provided with two separate JavaScript bundles: app.min.js is our regular application bundle and myComponent.min.js contains the code we've just written. I'll discuss how to deliver these bundles to the browser a little later.

2. Simplify the Setup With Babel

Ordinarily, I'd have to include two extra options when passing an object to the Loadable function, modules and webpack. These help Webpack identify which modules we should be including. Thankfully, we can obviate the need to include these two options with every component by using the react-loadable/babel plugin. This automatically includes these options for us:

I can include this plugin by adding it to my list of plugins in my .babelrc file, like so:

I'm now one step closer to lazy-loading our component. However, in my case I'm dealing with server-side rendering. Currently, the server will not be able to render our lazy-loaded components.

3. Rendering Components on the Server

In my server application I have a standard configuration that looks something like this:

The first step is going to be to instruct React Loadable that I want all modules to be preloaded. This allows me to decide which ones should be loaded immediately on the client. I do this by modifying my server/index.js file like so:

The next step is going to be to push all components I want to render to an array so we can later determine which components require immediate loading. This is so the HTML can be returned with the correct JavaScript bundles included via script tags (more on this later). For now, I'm going modify my server file like so:

Every time a component is used that requires React Loadable, it will be added to the modules array. This is an automatic process done by React Loadable, so this is all that's required on our part for this process.

Now we have a list of modules that we know will need to be rendered immediately. The problem we now face is mapping these modules to the bundles that Webpack has automatically produced for us.

4. Mapping Webpack Bundles to Modules

So now I've instructed Webpack to create myComponent.min.js and I know that MyComponent is being used immediately, so I need to load this bundle in the initial HTML payload we deliver to the user. Thankfully, React Loadable provides a way for us to achieve this, as well. In my client Webpack configuration file, I need to include a new plugin:

The loadable-manifest.json file will provide me a mapping between modules and bundles so that I can use the modules array I setup earlier to load the bundles I know I'll need. In my case this file might look something like this:

This will also require a common Webpack manifest file to include the mapping between modules and files for internal Webpack purposes. I can do this by including another Webpack plugin:

5. Including Bundles in Your HTML

The final step in loading our dynamic bundles on the server is to include these in the HTML we deliver to the user. For this step I'm going to combine the output of steps 3 and 4. I can start by modifying the server file I created above:

In this I've imported the manifest and asked React Loadable to create an array with module/bundle mappings. The only thing left for me to do is to render these bundles to an HTML string:

6. Load the Server-Rendered Bundles on the Client

The final step to using the bundles that we've loaded on the server is to consume them on the client. Doing this is simple—I can just instruct React Loadable to preload any modules it's found to be immediately available:

Conclusion

Following this process, I can split my application bundle into as many smaller bundles as I need. In this way, my app sends less to the user and only when they need it. I've reduced the amount of code that needs to be sent so that it can be sent faster. This can have significant performance gains for larger applications. It can also set smaller applications up for rapid growth should the need arise. 


by Luke Jones via Envato Tuts+ Code

Design Better UX With Vue.js Transitions and Animations

Transitions and animations are an important design pattern whose aim is to improve the user experience (UX) by making the user interface (UI) more natural and intuitive. 

Most people think that the purpose of transitions and animations is to engage the user's attention, and this is true to some extent. In certain contexts, such as game websites, where attractiveness and entertainment take precedent, it is justified. However, in most websites, engagement should be the secondary role, while the main role of any transitions or animations should be for communication.

And that will be the subject of this tutorial. We'll explore how transitions and animations can communicate effectively, and we'll see how to use them in the context of Vue.js. Of course, to apply the principles discussed below, you can use any other library or framework (such as React or Angular), or plain CSS transitions and animations.

Note: To follow this tutorial, you should have at least some basic knowledge about Vue.js. If you need to get up to speed, try our beginner's course, Get Started With Vue.

  • Vue.js
    Get Started With Vue
    Lawrence Turton

Why Are Transitions and Animations So Important?

In the real world, things don't just appear and disappear suddenly. They move smoothly, they change gradually. In a house, we see people entering or leaving the rooms. On the road, we see cars approaching or moving away. Even at different speeds, their movement is continuous. So to make an interface familiar and easier to understand, we need to mimic some aspects of this real-world behavior in our websites and applications.

This is the role of transitions and animations. They smooth changes between states. They show and explain what happens in a clear and predictable way. In most cases, without transitional effects, the user would be wondering what just occurred.

In modern websites, where interactivity plays a key role, the knowledge of how to use this powerful design pattern properly is crucial. The first thing human eyes perceive is movement. Human brains just love movement. Movement creates interest and catches the attention, but most importantly it delivers a message. The right message will lead to the right action. So proper use of transitions and animations can be the difference between a user making a purchase or leaving your website.

What Are Transitions and Animations?

A transition is simply the change that occurs while a thing moves between two states. The first state is the starting point, and the second state is the ending point. It's like when you open your car's window. The window first is in the closed state, and when you push the button, it gradually transitions to its opened state.

An animation is a series of transitions arranged in a logical order. This means that we have not only starting and ending points, but also several points in between. With transitions, we just go from A to B, or from B to C, and so on. With animations, if we want to go from A to E, for example, we need also to pass through B, C, and D. So the whole animation from A to E is actually made of four transitions, giving an illusion of continuous motion.

How Do Transitions and Animations Improve User Experience?

The first and foremost way in which transitions and animations improve UX is through communication. Just as real-life communication can improve human relationships, similarly in web development, communication can improve the UX of your website or application.

Harry Marks, award-winning broadcast designer, said:

If you don't have a story, no amount of graphic trickery will make it interesting.

So, if content is king and stories are all-important, the key is to present that content to the users in a pleasant and meaningful way. The story communicates a message to the users and must deliver it in a way that users can understand. Let's explore some examples:

  • If an object fades away, users know it disappeared.
  • If an object fades into view, users know the object has arrived.
  • If an image thumbnail zooms in after a mouse click or hover, users know that the zoomed image is the large version of the thumbnail.

All these transitions and animations are like road signs. They give the users clues about what to expect. And this leads to a more pleasant user experience.

There are also some important goals which transitions and animations help us to achieve in our application interfaces. They help us to:

  • maintain context while changing views
  • explain what just happened
  • show relationships between objects
  • focus user attention
  • improve perceived performance
  • create an illusion of virtual space

We'll see how this happens in action in the following examples, but let me first introduce you to Vue.js transitions and animations.

Getting Started With Vue.js Transitions and Animations

Working with Vue.js transitions and animations is easy. Vue.js provides a <transition> component which wraps the element or component you want to animate. It automatically adds three entering and three leaving CSS classes

v-enter, v-enter-active, and v-enter-to are responsible for the enter transition when the component is enabled or inserted.

v-leave, v-leave-active, and v-leave-to are responsible for the leave transition when the component is disabled or removed.

v-enter/v-leave and v-enter-to/v-leave-to define the starting and ending states of the transition. v-enter-active/v-leave-active define the transition's configuration, such as duration, easing function, etc.

The <transition> component can have a name property. If we define one, it will replace the default v- prefix in all classes. For example, if the name is set to "menu", the v-enter class will become menu-enter, and so on.

Let's now move on to the next section and see how all this is used in practice.

Vue.js Transitions and Animations Use Cases

What follows is a series of use cases which will illustrate the practical application of transitions and animations in Vue.js. 

Note: The CSS code unrelated to Vue.js is not shown in the examples for brevity. To see the full code, follow the link to CodePen at the end of each example.

Use Case 1: Dropdown Menu

In this first example, we have a nice dropdown menu which opens at mouse hover. The problem is that this happens too quickly, which is distracting and inconvenient to the users. To make the change between the opening and closing states more smooth and natural, we'll use CSS transitions. This helps users by explaining what just happened, so they can clearly see the connection between the drop-down button and the menu itself. 

Let's see this in action. First, we create our HTML template:

This creates a navbar menu with three buttons. The third button will open a drop-down menu, which is an unordered list wrapped with the <transition> component. We set the name attribute for the transition to dropdown. When the show property is true, the menu will appear, and vice versa.

In the JavaScript part, we create a new Vue instance and set the show property initially to false. So the menu will be hidden until we hover over it.

Next, we use the transition classes created by Vue to apply the desired CSS transition:

In the first CSS declaration, we make the menu transparent and slightly scaled down at the beginning of the enter transition and at the end of the leave transition. 

In its visible state, we make it fully opaque and scaled to its normal dimensions. In the last declaration, we set the settings for the transition. It will last 0.3 seconds and will have the ease-out easing function applied. Also, we set the transform-origin to top center so the menu will start to appear right below the drop-down button with a nice scroll-down effect.

Use Case 2: Flipping Form

In the second example, we have two forms. One is used to allow users to log in, while the other allows users to create a new profile. Going from one form to another by loading a new page can interrupt the user flow. So we'll use a flip transition, and thus the switch between the two forms will be sleek and easy. This will help to maintain context while changing views, making the user flow fluent and continuous.

Here is the template code:

Here we want to transition between two elements: the sign-in and sign-up forms. Because we are toggling between elements that have the same tag name (we wrap both forms with a <div> tag), they must have unique key attributes. Otherwise, Vue will only replace the content of the element. 

Also, because entering and leaving happens simultaneously by default, we need to use the mode attribute. We set it to out-in, so the current element will transition out first, and then, when complete, the other element will transition in.

In the script part, we set the front property to true. So the sign-in form will be displayed first:

And now let's move on to the CSS code:

We make the form transparent and rotated 90 degrees at the start of entering and at the end of leaving the transition. Then we set the transition's duration to 0.5 seconds.

Use Case 3: Modal Window

In the third example, we use a modal window to show users additional information. But the modal appears and disappears abruptly and merges with the background. To solve the problem, we'll use transitions so the modal will be zoomed in and zoomed out smoothly when it is opened or closed. Also, we'll dim the background while keeping the modal bright to create more contrast. This will focus the user's attention in a natural way.

Let's start with the template again:

In this example, we use custom transition classes. This way, we can use an animation library such as animate.css. We put the custom classes directly in the <transition> component and use the classes from the animate.css library. 

In the script part, we first register the modal component used in the template above. Then, in the Vue instance, we set several properties and one method, which will help us to toggle between visible and hidden state, and apply different classes for each one:

And here are the CSS classes:

The .blur class is applied when the modal is opened, and the .clear class when it is closed.

Use Case 4: To-Do List

In the last example, we have a simple to-do list app. It works fine, but when we add or remove items, they are inserted and removed instantly. Users can be easily confused about what is added and what is removed. To make the user experience more pleasant and predictable, we'll use an animation when the items are inserted or removed. This will show relationships between items and help users to orientate themselves and understand what's going on.

Here is the template:

In this example, we want to animate multiple items, so we need to use the <transition-group> component. Unlike <transition>, it renders an actual element. By default, it is <span>. But we actually need an unordered list, so we need to set the tag attribute to ul.

In the script part, we put some initial data in and create two methods responsible for adding and removing list items:

And here are the CSS classes:

In the CSS, we create an add-item animation. We use that animation in the enter transition. In the leave transition, we use the same animation, but reversed. This follows the Symmetry of Interaction principle.  

If you try the app at this stage, the items will be animated, but the list itself will just snap to its new place. To make it move smoothly, we need to do two things: first set the position to absolute in the leaving transition, and then add the move class which Vue provides especially for list transitions. 

Best Practices for Transitions and Animations

As you can see, transitions and animations are a powerful way to communicate and engage the user. If used correctly, they can greatly improve the UX. To make it easy to remember, I've prepared the following list of best practices for employing transitions and animations in your websites or applications.

  • The key to making a good transition is the balance of speed. The right duration differs for each individual use case, but as a rule of thumb, a transition should look and feel natural—not too fast, not too slow. 
  • Rapid movement and movement towards the user are considered more important than slow movement and movement away from the user.
  • Avoid transitional effects which annoy and distract rather than communicate. The user's attention must be gently guided and directed, not forcibly commanded and dominated.
  • Avoid overuse of transitions by only using them to communicate change in the interface.
  • Usually, transitions should be reflexive. If users create an object and it slides in, then when it is removed it should slide out with a reverse transition. This illustrates the Symmetry of Interaction principle.
  • To make the transitions more discoverable, you should keep them near the user's area of focus. This also will help feel them less like advertising.

Conclusion

I hope that after reading this post you now have a much better understanding of what transitions and animations are and how to use them correctly. You've also seen how to apply them, in the context of Vue.js, to your website or application's user interface, making the UX better and users happy.

This post only scratches the surface about Vue.js transitions and animations. So here are some useful links for further explorations:


by Ivaylo Gerchev via Envato Tuts+ Code

Seedlip

Online store & brand destination for the world’s first non-alcoholic spirits.
by via Awwwards - Sites of the day

How to Maximize the Exposure of Your Videos: A Strategic Plan

Is video a key part of your social media strategy? Wondering how to get more visibility for the videos you create? In this article, you’ll discover a step-by-step plan to help you post, promote, and distribute your videos more effectively. Why Your Business Needs a Video Distribution and Promotion Strategy Right now, video is the […]

The post How to Maximize the Exposure of Your Videos: A Strategic Plan appeared first on Social Media Examiner.


by Desiree Martinez via Social Media Examiner

Knowing When to Change: The Journey: Season 2, Episode 10

Ever have a moment where it becomes crystal clear that something needs to change? Then watch the Journey, Social Media Examiner’s episodic video documentary that shows you what really happens inside a growing business. Watch the Journey In episode 10, Michael Stelzner (founder of Social Media Examiner) realizes lots of things he’s doing must stop. […]

The post Knowing When to Change: The Journey: Season 2, Episode 10 appeared first on Social Media Examiner.


by Michael Stelzner via Social Media Examiner

Social Media Optimization: How to Use Instagram Stories to Boost Business (infographic)

The age of social media has made it so essential that pretty much everyone and everything needs a social media account, at least if they want success or renown. Instagram (IG) has become an exceedingly popular platform particularly for businesses that want to market their products and boost their...

[ This is a content summary only. Visit our website https://ift.tt/1b4YgHQ for full links, other content, and more! ]

by Irfan Ahmad via Digital Information World

Social Media Ad Boom Continues [CHART]

Despite the fact that platforms such as Facebook and Twitter have come under fire this year for allowing bots and fake profiles to spread false information and sow hatred and division, social media advertising continues to grow in the United States. According to IAB’s latest Internet Advertising...

[ This is a content summary only. Visit our website https://ift.tt/1b4YgHQ for full links, other content, and more! ]

by Web Desk via Digital Information World