Day 14/30 - Talk JavaScript To Me: Performance Optimisation

Day 14/30 - Talk JavaScript To Me: Performance Optimisation

Let's start with a silly programming joke, shall we ? ??

What’s the object-oriented way to become wealthy?

Inheritance.??        

Are you looking to take your JavaScript skills to the next level by making your code faster and more efficient? Here are some advanced tips and techniques, including code splitting, Webpack optimisation, and code minimisation. Let's dive in!

1. Code Splitting

Code splitting is a powerful technique to improve the load time of your JavaScript applications by breaking down your code into smaller chunks that can be loaded on demand.

// Before: Single bundled file
import { largeModule } from './largeModule';
largeModule.doSomething();

// After: Code splitting using dynamic import
import('./largeModule').then(module => {
  module.largeModule.doSomething();
});        

2. Webpack Code Splitting

Webpack is a popular module bundler that supports code splitting out of the box. It helps in creating separate bundles for different parts of your application, which can be loaded dynamically.

// Webpack configuration for code splitting
module.exports = {
  entry: {
    main: './src/index.js',
    vendor: './src/vendor.js',
  },
  output: {
    filename: '[name].[contenthash].js',
    path: __dirname + '/dist',
  },
  optimization: {
    splitChunks: {
      chunks: 'all',
    },
  },
};        

3. Code Minimisation

Minimisation reduces the size of your JavaScript files by removing unnecessary characters, such as white spaces and comments, making your code more compact and faster to load.

// Before minimisation
function add(a, b) {
  return a + b;
}

// After minimisation (using a tool like UglifyJS or Terser)
function add(a,b){return a+b}        

4. Tree Shaking

Tree shaking is a technique used to remove dead code from your bundle. It ensures that only the necessary code is included in the final bundle.

// Before tree shaking
import { usedFunction, unusedFunction } from './module';
usedFunction();

// Webpack configuration to enable tree shaking
module.exports = {
  mode: 'production',
  optimization: {
    usedExports: true,
  },
};
        

5. Lazy Loading

Web Workers allow you to run scripts in background threads, freeing up the main thread to perform UI updates and other tasks.

// Main thread
const worker = new Worker('worker.js');
worker.postMessage('Hello, Worker!');

// worker.js
self.onmessage = function(event) {
  console.log(event.data); // 'Hello, Worker!'
};        

Further readings

https://webpack.js.org/guides/code-splitting/

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Performance


要查看或添加评论,请登录

Prakash Pun的更多文章