DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • How to Build Scalable Mobile Apps With React Native: A Step-by-Step Guide
  • Scaling Mobile App Performance: How We Cut Screen Load Time From 8s to 2s
  • Interrupt Testing: Bulletproof Your App for the Real World
  • In-App Browsers in Mobile Apps: Benefits, Challenges, Solutions

Trending

  • Beyond Code Coverage: A Risk-Driven Revolution in Software Testing With Machine Learning
  • How to Ensure Cross-Time Zone Data Integrity and Consistency in Global Data Pipelines
  • FIPS 140-3: The Security Standard That Protects Our Federal Data
  • Scaling DevOps With NGINX Caching: Reducing Latency and Backend Load
  1. DZone
  2. Coding
  3. JavaScript
  4. 3 Code Splitting Patterns For Vue.js and Webpack

3 Code Splitting Patterns For Vue.js and Webpack

In this article, a DZone MVB and Vue.js expert shows three methods you can use for architecting an app for code splitting using Vue and Webpack.

By 
Anthony Gore user avatar
Anthony Gore
DZone Core CORE ·
Updated Feb. 10, 20 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
13.7K Views

Join the DZone community and get the full member experience.

Join For Free

code splitting a single page app is a great way to improve its initial loading speed. since a user doesn't have to download all the code in one hit, they'll be able to see and interact with the page sooner. this will improve ux, especially on mobile, and it's a win for seo, as google penalizes slow loading sites.

last week i wrote about how to code split a vue.js app with webpack . long story short, anything you wrap in a single file component can easily be code split, as webpack can create a split point when it imports a module, and vue is happy to load a component asynchronously.

i believe the hardest part of code splitting is not getting it to work, but knowing where and when to do it. i'd go as far as to say that code splitting needs to be an architectural consideration when designing your app.

in this article i'll present three patterns for code splitting a vue.js single page app:

  • by page
  • by page fold
  • by condition

image title

1. by page

splitting your code by page is an obvious place to start. take this simple app, which has three pages:

image title

if we make sure each page is represented by its own single file component, e.g. home.vue , about.vue , and contact.vue , then we can use webpack's dynamic import function to split each into a separate build file. then, when the user visits a different page, webpack will asynchronously load the requested page's file.

this is trivial to implement if you're using vue-router , as your pages will already need to be in separate components.

routes.js

const home = () => import(/* webpackchunkname: "home" */ './home.vue');
const about = () => import(/* webpackchunkname: "about" */ './about.vue');
const contact = () => import(/* webpackchunkname: "contact" */ './contact.vue');

const routes = [
  { path: '/', name: 'home', component: home },
  { path: '/about', name: 'about', component: about },
  { path: '/contact', name: 'contact', component: contact }
];

take a look at stats generated when we build this code. each page is in its own file, but also note there's a main bundle file called build_main.js , which contains any common code as well as the logic for asynchronously loading the other files. it will need to be loaded no matter what route the user visits.

image title

now let's say i load the contact page from the url http://localhost:8080/#/contact . when i check the network tab i see the following files have loaded:

image title

notice that the initiator of build_main.js is (index) . this means that index.html requested the script, which is what we'd expect. but the initiator of build_1.js is bootstrap_a877... . this is the weback script that is responsible for asynchronously loading files. this script is added to the build automatically when you use webpack's dynamic import function. the important point is that build_1.js did not block the initial page load.

2. below the fold

below the "fold" is any part of the page that is not visible in the viewport when the page initially loads. you can asynchronously load this content since the user will usually take a second or two to read above the fold before they scroll down, especially on the first time they visit the site.

image title

in this example app, i consider the fold line to be just below the masthead. so let's include the nav bar and the masthead on the initial page load, but anything below that can be loaded afterward. i'll now create a component called belowfold and abstract the relevant markup into that:

home.vue

<template>
  <div>
    <div class="jumbotron">
        <h1>jumbotron heading</h1>
        ...
    </div>

    <below-fold></below-fold>

    <!--all the code below here has been put into-->
    <!--into the above component-->
    <!--<div class="row marketing">
      <div class="col-lg-6">
        <h4>subheading</h4>
        <p>donec id elit non mi porta gravida at eget metus. maecenas faucibus mollis interdum.</p>
        ...
      </div>
      ...
    </div>-->

  </div>
</template>
<script>

  const belowfold = () => import(
    /* webpackchunkname: "below-fold" */ './belowfold.vue'
  );

  export default {
    ...
    components: {
        belowfold
    }
  }
</script>

belowfold.vue

<template>
  <div class="row marketing">
    <div class="col-lg-6">
      <h4>subheading</h4>
      <p>donec id elit non mi porta gravida at eget metus. maecenas faucibus mollis interdum.</p>
      ...
    </div>
    ...
  </div>
</template>

we will now see the below-fold chunk in its own separate file when we bundle the code:

image title

note: the below-fold chunk is very small (1.36kb) and it seems hardly worth bothering to split this out. but that's only because this is a demo app with very little content. in a real app, the majority of the page is likely to be below the fold, so there might be a ton of code there including css and js files for any sub components.

3. conditional content

another good candidate for code splitting is anything that is shown conditionally . for example, a modal window, tabs, drop-down menus, etc.

this app has a modal window that opens when you press the "sign up today" button:

image title

as before, we just move the modal code into its own single file component:

home.vue

<template>
  <div>
    <div class="jumbotron">...</div>

    <below-fold></below-fold>

    <home-modal v-if="show" :show="show"></home-modal>
  </div>
</template>
<script>

  const belowfold = () => import(
    /* webpackchunkname: "below-fold" */ './belowfold.vue'
  );
  const homemodal = () => import(
    /* webpackchunkname: "modal" */ './homemodal.vue'
  );

  export default {
    data() {
      return {
        show: false
      }
    },
    components: {
      homemodal,
      belowfold
    }
  }
</script>

homemodal.vue

<template>
    <modal v-model="show" effect="fade">...</modal>
</template>
<script>
  import modal from 'vue-strap/src/modal.vue';

  export default {
    props: ['show'],
    components: {
        modal
    }
  }
</script>

notice that i've put a v-if on the modal. the boolean show controls the opening/closing of the modal, but it will also conditionally render the modal component itself. since on page load it's false, the code will only get downloaded when the modal is opened.

this is cool because if a user never opens the modal, they never have to download the code. the only downside is that it has a small ux cost: the user has to wait after they press the button for the file to download.

after we build again, here's what our output looks like now:

image title

another ~5kb we don't have to load up front.

conclusion

those are three ideas for architecting an app for code splitting. i'm sure there are other ways to do it if you use your imagination!

mobile app Vue.js

Published at DZone with permission of Anthony Gore, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How to Build Scalable Mobile Apps With React Native: A Step-by-Step Guide
  • Scaling Mobile App Performance: How We Cut Screen Load Time From 8s to 2s
  • Interrupt Testing: Bulletproof Your App for the Real World
  • In-App Browsers in Mobile Apps: Benefits, Challenges, Solutions

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!