Skip to content

Defer Custom and Lightbox Script Loading #2

@stungeye

Description

@stungeye

The mobile PageSpeed score for the notes is negatively affected by all the css and js being loaded in the document head.

The custom mycode.js script tag could be marked as defer and the loading of the lightbox js could be moved into the mycode.js in the same way that the codepen js is being loaded using the DOM.

The head_custom.html would become:

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/glightbox/dist/css/glightbox.min.css">
<script defer type="text/javascript" src="{{ '/assets/js/mycode.js' | relative_url }}"></script>

And mycode would become:

document.addEventListener("DOMContentLoaded", function (event) {
  const glightboxScript = document.createElement("script");
  glightboxScript.src = "https://cdn.jsdelivr.net/gh/mcstudios/glightbox/dist/js/glightbox.min.js";
  document.head.appendChild(glightboxScript);
  glightboxScript.onload = () => {
    if (GLightbox) {
      GLightbox({ selector: "img" });
    }
  };

  const codepens = document.querySelectorAll(".codepen");
  if (codepens.length > 0) {
    const codepenScript = document.createElement("script");
    codepenScript.src = "https://static.codepen.io/assets/embed/ei.js";
    document.head.appendChild(codepenScript);
  }
});

The glightbox CSS could also be deferred using this trick.

Testing will be needed to see if this change is even worthwhile.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions