Invoke a javascript function after page loading is finished?

1.1k views Asked by At

I use CookieBot in our html pages. CookieBot javascript doesn't load in test environment and throws a net::ERR_ABORTED 404 error.

When this happens, the loading spinner in the page keeps displaying after the page loading has been completed.

I tried following options to invoke a listener after page loading is completed. But none of them works:

document.addEventListener("load", (e) => {
    console.log("document load");
});

document.addEventListener("DOMContentLoaded", function(event) {
    console.log("DOMContentLoaded");
});

$(document).ready(function() {
    console.log("ready!");
});

$(document).ready(function() {
    console.log("document is ready");
});

$(window).on("load", function(){
    console.log("window load!");
});

window.onload = function () {
    console.log("window onload!");
};

I guess CookieBot script overrides my listeners. Here is an example where listener is not invoked. When you remove the CookieBot script it runs: https://jsfiddle.net/hkarakose/4by26Lr3/1/

How can I invoke a function after page loading is finished?

3

There are 3 answers

0
Halil On

Although @davilink92's answer works, I solved this issue in a more practical way.

I attached external script loading to window load event:

window.addEventListener('load', function () {
    $.getScript("https://consent.cookiebot.com/uc.js?cbid=d180eb7a-8f13-4549-bacc-6d4a6dfb5da8&culture=en");
    $("#global-loader").fadeOut("slow");
});

In this way, the script couldn't prevent the window load event listener to be invoked by the browser. And thus, I was able to remove the loading spinner after page is loaded.

0
Nathan Bardon On

I have the habit to use document.addEventListener("load", (e) => {console.log("loaded"); })

Can you show us more code to see if your problem is here? I think all of yours tests are correct and I dont understand why it isnt working.

3
davilink92 On

You can invoke a function after page loading with:

window.onload = function() {
 //here you can write your function and invoke it.
}

Edit:

Maybe I didn't understand your request, but now I'm reading more carefully.

The problem is in the script, right? If you insert the script on HEAD, it will be loaded first.

You could insert the type of the script in this way: type = "text / plain" with a data-attribute: data-attribute = "script-cookie".

Then change the type once everything has been loaded, like this:

window.onload = function () {
       var allPrefScript = document.querySelectorAll ("script [data-attribute =" script-cookie "]");
allPrefScript [0] .setAttribute ("type", "text / javascript");
}