This problem is not a simple problem of just creating and injecting the script file.
I want to optimize my website which loads script files of google ads.
Problem: When script files of google ads load parallelly with HTML files then page load speed drastically decreased.
Solution I came up with: I decided to load the script files of google ads after the webpage is 100% completely loaded (or even 100-200miliseconds after page 100% loaded)
Solutions I tried are as follows with details:
Created a function to load script file and used window.onload = loadGoogleSyndication(). But it actually loads the script before the complete loading of the HTML document. (i can observe it in the speed test of the site)
function loadGoogleSyndication() {
const googleSyndication = document.createElement('script');
googleSyndication.type = 'text/javascript';
googleSyndication.async = true;
googleSyndication.src = 'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js';
const script = document.getElementsByTagName('script')[0];
script.parentNode.insertBefore(googleSyndication, script);
}
window.onload = loadGoogleSyndication()
Secondly I used document.onload = loadGoogleSyndication(). But again it loads file before complete loading of page.
window.onload = loadGoogleSyndication()
window.addEventlister("load", loadGoogleSyndication())Only solution that worked:
I use setTimeout property and loaded the file after 2.5 sec and then it worked. (2.5 sec can be 2sec also for fast internet connection)
This works 👇
window.addEventListener("load", function () {
setTimeout(() => {
loadGoogleSyndication();
}, 2500);
}, true);
But is there any solution other than this where the script loads exactly after(or after 100 milliseconds) 100% HTML file loaded? Because using setTimeout property is throwing a knife in darkness we exactly don't know when the file HTML file load is completed.
One other solution could be to load file after window scrolled window.onscroll, but I don't want to use it.
Try DOMContentLoaded which fires only when all the nodes in the page have been constructed in the DOM tree.
function loadGoogleSyndication() {
const googleSyndication = document.createElement('script');
googleSyndication.type = 'text/javascript';
googleSyndication.async = true;
googleSyndication.src = 'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js';
const script = document.getElementsByTagName('script')[0];
script.parentNode.insertBefore(googleSyndication, script);
}
window.addEventListener('DOMContentLoaded', loadGoogleSyndication)