Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement lazy loading for third-party JavaScript to improve page load speeds #511

Merged
merged 4 commits into from
Sep 25, 2024

Conversation

khaterdev
Copy link
Collaborator

@khaterdev khaterdev commented Sep 25, 2024

Changes

This PR introduces lazy loading for third-party JavaScript, specifically advertisements and Google Analytics, to improve page load speeds. The changes include:

  • Delaying the loading of third-party scripts by 3 seconds after the initial app rendering
  • Implementing this delay in the App component within app/root.tsx
  • Using setTimeout and requestAnimationFrame to manage the delayed loading of Google Tag Manager and Ezoic scripts
  • Ensuring that the scripts are loaded asynchronously to minimize impact on app performance

Key updates:

  1. Increased delay from 2 to 3 seconds for third-party script loading
  2. Added requestAnimationFrame to further optimize the loading process
  3. Adjusted the script loading logic for better performance

Motivation

These changes aim to improve the initial load time and overall performance of our application, especially on mobile devices. This is crucial because:

  1. Our mobile load speeds currently need improvement
  2. Google's mobile-first indexing initiative will exclusively crawl and index all sites using its mobile Googlebot after July 5, 2024
  3. We want to keep ads while improving performance

This should result in:

  • Faster perceived load time for users
  • Better Core Web Vitals scores
  • Improved mobile experience
  • Better indexing by Google post July 2024

Related Issues

Addresses #507 - Improve page load speeds

Summary by CodeRabbit

  • New Features

    • Implemented a controlled loading mechanism for Google Tag Manager and Ezoic scripts, enhancing performance by introducing a 3-second delay before loading.
  • Bug Fixes

    • Removed inline script tags for Google Tag Manager and Ezoic, improving code organization and maintainability.
  • Style

    • Updated string literals to use single quotes for consistency and improved formatting in the blog component.

Copy link
Contributor

coderabbitai bot commented Sep 25, 2024

Walkthrough

The changes introduce a useEffect hook in the App function to load Google Tag Manager and Ezoic scripts after a 3-second delay. This approach replaces the previous inline script tags in the JSX return statement, allowing for a more controlled loading mechanism. The Ezoic script includes a callback to initialize the ezstandalone object and execute various methods related to Ezoic functionalities. Additionally, the app/routes/blog.wow.tldr.tsx file underwent formatting changes, primarily switching from double quotes to single quotes for string literals and minor adjustments for JSX readability.

Changes

Files Change Summary
app/root.tsx Introduced useEffect to load Google Tag Manager and Ezoic scripts after a 3-second delay; removed inline script tags from JSX return statement.
app/routes/blog.wow.tldr.tsx Reformatted string literals to use single quotes; adjusted JSX element formatting for readability; no logic changes.

Possibly related PRs

Poem

In the code where rabbits hop,
Scripts now load without a stop.
Three seconds wait, then watch them play,
Tag Manager and Ezoic sway.
A dance of data, swift and bright,
In the app, a joyful sight! 🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 97be4f5 and 1495ba3.

📒 Files selected for processing (1)
  • app/routes/blog.wow.tldr.tsx (14 hunks)
✅ Files skipped from review due to trivial changes (1)
  • app/routes/blog.wow.tldr.tsx

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (2)
app/root.tsx (2)

247-282: Approve with suggestions: Lazy loading implementation for third-party scripts

The implementation of lazy loading for Google Tag Manager and Ezoic scripts is a good approach to improve initial page load times. However, there are some areas for potential improvement:

  1. Consider using a more dynamic approach for the delay, such as after the main content has loaded or based on network conditions.
  2. Implement error handling for script loading failures.
  3. Consider the impact on analytics data accuracy for very short user sessions.

To improve readability and maintainability, consider refactoring the useEffect hook into smaller, more focused functions:

const loadGoogleTagManager = () => {
  // GTM loading logic
};

const loadEzoicScript = () => {
  // Ezoic loading logic
};

useEffect(() => {
  const timer = setTimeout(() => {
    window.requestAnimationFrame(() => {
      loadGoogleTagManager();
      loadEzoicScript();
    });
  }, 3000);

  return () => clearTimeout(timer);
}, []);

This refactoring will make the code easier to understand and maintain.


247-282: Summary: Lazy loading implementation aligns with PR objectives

The implementation of lazy loading for Google Tag Manager and Ezoic scripts aligns well with the PR objectives of improving page load speeds and addressing mobile performance issues. By delaying the loading of these third-party scripts, the initial page load time should improve, potentially leading to better Core Web Vitals scores and an enhanced mobile experience.

However, to fully realize the benefits and prepare for Google's mobile-first indexing initiative, consider the following recommendations:

  1. Implement more dynamic script loading based on user interaction or network conditions.
  2. Add error handling and fallback mechanisms for script loading failures.
  3. Use Subresource Integrity (SRI) for enhanced security when loading third-party scripts.
  4. Consider using requestIdleCallback for more intelligent script loading timing.
  5. Monitor and analyze the impact on Core Web Vitals scores, especially Largest Contentful Paint (LCP) and First Input Delay (FID), to ensure the changes are having the desired effect.

These enhancements will further improve the user experience and help ensure readiness for Google's mobile-first indexing after July 5, 2024.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 8041b19 and 97be4f5.

📒 Files selected for processing (1)
  • app/root.tsx (1 hunks)
🔇 Additional comments not posted (1)
app/root.tsx (1)

263-266: Security consideration: Third-party script loading

Loading scripts from third-party sources, like Ezoic, introduces potential security risks if the source is compromised. Consider implementing Subresource Integrity (SRI) to ensure the integrity of the loaded script:

const script = document.createElement('script');
script.src = '//www.ezojs.com/ezoic/sa.min.js';
script.integrity = 'sha384-HASH_VALUE_HERE'; // Replace with actual hash
script.crossOrigin = 'anonymous';
script.async = true;
document.body.appendChild(script);

To verify the current integrity of the Ezoic script, you can run the following command:

This will generate the integrity hash that you can use in the script tag.

app/root.tsx Outdated
Comment on lines 247 to 282
useEffect(() => {
const timer = setTimeout(() => {
window.requestAnimationFrame(() => {
// Load Google Tag Manager
;(function (w, d, s, l, i) {
w[l] = w[l] || []
w[l].push({ 'gtm.start': new Date().getTime(), event: 'gtm.js' })
var f = d.getElementsByTagName(s)[0],
j = d.createElement(s),
dl = l != 'dataLayer' ? '&l=' + l : ''
j.async = true
j.src = 'https://www.googletagmanager.com/gtm.js?id=' + i + dl
f.parentNode.insertBefore(j, f)
})(window, document, 'script', 'dataLayer', 'GTM-WH4KFG5')

// Load Ezoic script
const script = document.createElement('script')
script.src = '//www.ezojs.com/ezoic/sa.min.js'
script.async = true
document.body.appendChild(script)

script.onload = function () {
window.ezstandalone = window.ezstandalone || {}
ezstandalone.cmd = ezstandalone.cmd || []
ezstandalone.cmd.push(function () {
ezstandalone.define(118, 116)
ezstandalone.refresh()
ezstandalone.enable()
ezstandalone.display()
})
}
})
}, 3000) // Delay of 3000ms (3 second)

return () => clearTimeout(timer)
}, [])
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Performance suggestion: Consider using requestIdleCallback

To further optimize performance and ensure analytics accuracy, consider using requestIdleCallback instead of a fixed timeout. This will load the scripts when the browser is idle, potentially earlier than 3 seconds if possible, or later if the main thread is busy:

useEffect(() => {
  const loadScripts = () => {
    window.requestAnimationFrame(() => {
      loadGoogleTagManager();
      loadEzoicScript();
    });
  };

  if ('requestIdleCallback' in window) {
    window.requestIdleCallback(loadScripts, { timeout: 3000 });
  } else {
    // Fallback for browsers that don't support requestIdleCallback
    setTimeout(loadScripts, 3000);
  }
}, []);

This approach balances performance optimization with ensuring the scripts load within a reasonable timeframe.

Copy link

cloudflare-workers-and-pages bot commented Sep 25, 2024

Deploying saddlebag-with-pockets with  Cloudflare Pages  Cloudflare Pages

Latest commit: 1495ba3
Status: ✅  Deploy successful!
Preview URL: https://cbd3fbeb.saddlebag-with-pockets.pages.dev
Branch Preview URL: https://lazy-load-third-party-js.saddlebag-with-pockets.pages.dev

View logs

Copy link

sonarcloud bot commented Sep 25, 2024

@cohenaj194 cohenaj194 merged commit 676e936 into master Sep 25, 2024
5 checks passed
@cohenaj194 cohenaj194 deleted the lazy-load-third-party-js branch September 25, 2024 20:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants