Last active
September 2, 2024 09:22
-
-
Save akojif/c2e981c58d6b938b2f33409235360456 to your computer and use it in GitHub Desktop.
Optimize Core Web Vitals: Fix Render-Blocking JavaScript with Google Analytics
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function loadGoogleAnalytics() { | |
| return new Promise((resolve, reject) => { | |
| // Create the script element for Google Analytics | |
| const script = document.createElement("script"); // change the variable to 'var' if Elementor | |
| script.async = true; | |
| script.src = | |
| "https://www.googletagmanager.com/gtag/js?id=GA_TRACKING_ID_HERE"; | |
| //script.onload = resolve; | |
| script.onload = () => { | |
| // Remove this function after testing and un-comment the line above this | |
| console.log("GA script loaded"); | |
| resolve(); | |
| }; | |
| script.onerror = reject; | |
| document.head.appendChild(script); | |
| }); | |
| } | |
| async function initGoogleAnalytics() { | |
| try { | |
| await loadGoogleAnalytics(); // Wait for GA script to load | |
| window.dataLayer = window.dataLayer || []; | |
| function gtag() { | |
| dataLayer.push(arguments); | |
| } | |
| gtag("js", new Date()); | |
| gtag("config", "GA_TRACKING_ID_HERE"); | |
| // gtag('config', 'GA_TRACKING_ID_HERE', { 'debug_mode': true }); // Optional to start debug mode | |
| console.log("Google Analytics initialized successfully."); // Remove after testing | |
| } catch (error) { | |
| console.error("Failed to load Google Analytics: ", error); | |
| } | |
| } | |
| // Execute the function to load and initialize GA | |
| initGoogleAnalytics(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment