Skip to content

Instantly share code, notes, and snippets.

@jdbruxelles
Last active November 9, 2023 20:08
Show Gist options
  • Save jdbruxelles/68b64fbbe576731c75f4cc2901bbe766 to your computer and use it in GitHub Desktop.
Save jdbruxelles/68b64fbbe576731c75f4cc2901bbe766 to your computer and use it in GitHub Desktop.
What is the most effective way of writing JS codes for better web performance?

Basic tricks for better Web Performance with JavaScript

Effective JavaScript Practices for Optimized Web Performance

Boost your web application's performance by adhering to the following steps:

  1. Reduce activity in loops: Place statements or assignments outside the loop whenever possible to enhance loop execution speed.

    let arr = [1, 2, 3, 4, 5];
    // BAD
    for (let i = 0; i < arr.length; i++) { ... }
    
    // BETTER
    let length = arr.length; // Declare outside of loop
    for (let i = 0; i < length; i++) { ... }

    While the bad approach is acceptable for smaller arrays, when dealing with significantly larger arrays, the code's practice of recalculating the array size in every iteration of the loop may lead to delays and inefficiencies.

  2. Reduce DOM access: Particularly crucial for large websites. If a DOM element is accessed multiple times, store it in a local variable after the first access.

    const demo = document.getElementById("demo"); // Store in local variable
    demo.innerHTML = "Hello";
    demo.style.color = "red";
  3. Avoid unnecessary variables and functions: Each variable and function takes up memory. If they are not necessary, they can slow down your application.

    let firstName = "John";
    let lastName = "Doe";
    
    // Recommended:
    document.getElementById("demo").innerHTML = `${firstName} ${lastName}`;
    
    // Not recommended:
    let fullName = `${firstName} ${lastName}`;
    document.getElementById("demo").innerHTML = fullName;
  4. Load scripts at the End: Position your scripts at the bottom of the page body to allow the browser to load the page first. This prevents parsing and rendering activities from being blocked.

    <body>
      <!-- Your HTML code -->
      <!-- Load script at the end -->
    </body>

    The HTTP specification states that browsers are advised not to simultaneously download more than two components.

    Another option is to include defer="true" in the script tag. This attribute indicates that the script should be executed after the page has completed parsing, but it is applicable only to external scripts.

    If applicable, you can insert your script into the page through code after the page has loaded:

    <script>
      window.onload = () => {
        const element = document.createElement("script");
        element.src = "/script.js";
        document.body.appendChild(element);
      };
    </script>

    Or use module with import/export statements.

  5. Avoid with keyword: The with keyword negatively impacts speed and complicates JavaScript scopes. It is not permitted in strict mode.

    // Not recommended:
    with (document.getElementById("demo").style) {
      color = "red";
      backgroundColor = "blue";
    }
    
    // Recommended:
    const demoStyle = document.getElementById("demo").style;
    demoStyle.color = "red";
    demoStyle.backgroundColor = "blue";
  6. Declare local variables: Always declare local variables using the var, let or const keywords to prevent them from becoming global variables.

    function example() {
      let localVariable = "I'm local!"; // Declare as local variable
    }
  7. Use Proper Data Structures.

    // Using Map for key-value associations
    let map = new Map();
    map.set("name", "John");
    console.log(map.get("name")); // John
  8. Minify and Compress Your Code: There are many online tools and npm packages for this, like UglifyJS, Terser, etc.


For additional tricks about improving page load speed, see this list.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment