Invoke a javascript function after page loading is finished? - javascript

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?

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");
}

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.

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.

Related

How to wait to execute JS until readyState == Complete for document and window? [duplicate]

I need to execute some JavaScript code when the page has fully loaded. This includes things like images.
I know you can check if the DOM is ready, but I don’t know if this is the same as when the page is fully loaded.
That's called load. It came waaaaay before DOM ready was around, and DOM ready was actually created for the exact reason that load waited on images.
window.addEventListener('load', function () {
alert("It's loaded!")
})
For completeness sake, you might also want to bind it to DOMContentLoaded, which is now widely supported
document.addEventListener("DOMContentLoaded", function(event){
// your code here
});
More info: https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded
Usually you can use window.onload, but you may notice that recent browsers don't fire window.onload when you use the back/forward history buttons.
Some people suggest weird contortions to work around this problem, but really if you just make a window.onunload handler (even one that doesn't do anything), this caching behavior will be disabled in all browsers. The MDN documents this "feature" pretty well, but for some reason there are still people using setInterval and other weird hacks.
Some versions of Opera have a bug that can be worked around by adding the following somewhere in your page:
<script>history.navigationMode = 'compatible';</script>
If you're just trying to get a javascript function called once per-view (and not necessarily after the DOM is finished loading), you can do something like this:
<img src="javascript:location.href='javascript:yourFunction();';">
For example, I use this trick to preload a very large file into the cache on a loading screen:
<img src="bigfile"
onload="this.location.href='javascript:location.href=\'javascript:doredir();\';';doredir();">
Try this it Only Run After Entire Page Has Loaded
By Javascript
window.onload = function(){
// code goes here
};
By Jquery
$(window).bind("load", function() {
// code goes here
});
Try this code
document.onreadystatechange = function () {
if (document.readyState == "complete") {
initApplication();
}
}
visit https://developer.mozilla.org/en-US/docs/DOM/document.readyState for more details
Javascript using the onLoad() event, will wait for the page to be loaded before executing.
<body onload="somecode();" >
If you're using the jQuery framework's document ready function the code will load as soon as the DOM is loaded and before the page contents are loaded:
$(document).ready(function() {
// jQuery code goes here
});
the window.onload event will fire when everything is loaded, including images etc.
You would want to check the DOM ready status if you wanted your js code to execute as early as possible, but you still need to access DOM elements.
You may want to use window.onload, as the docs indicate that it's not fired until both the DOM is ready and ALL of the other assets in the page (images, etc.) are loaded.
In modern browsers with modern javascript (>= 2015) you can add type="module" to your script tag, and everything inside that script will execute after whole page loads. e.g:
<script type="module">
alert("runs after") // Whole page loads before this line execute
</script>
<script>
alert("runs before")
</script>
also older browsers will understand nomodule attribute. Something like this:
<script nomodule>
alert("tuns after")
</script>
For more information you can visit javascript.info.
And here's a way to do it with PrototypeJS:
Event.observe(window, 'load', function(event) {
// Do stuff
});
The onload property of the GlobalEventHandlers mixin is an event
handler for the load event of a Window, XMLHttpRequest, element,
etc., which fires when the resource has loaded.
So basically javascript already has onload method on window which get executed which page fully loaded including images...
You can do something:
var spinner = true;
window.onload = function() {
//whatever you like to do now, for example hide the spinner in this case
spinner = false;
};
Completing the answers from #Matchu and #abSiddique.
This:
window.addEventListener('load', (event) => {
console.log('page is fully loaded');
});
Is the same as this but using the onload event handler property:
window.onload = (event) => {
console.log('page is fully loaded');
};
Source:
https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event
Live example here:
https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event#live_example
If you need to use many onload use $(window).load instead (jQuery):
$(window).load(function() {
//code
});
2019 update: This is was the answer that worked for me. As I needed multiple ajax requests to fire and return data first to count the list items.
$(document).ajaxComplete(function(){
alert("Everything is ready now!");
});

How to wait to finish loading page on button click using JavaScript/JQuery?

I am having an Anchor link, on click of Anchor link, I am registering new JavaScript file html page.
On registering the JavaScript file dynamically, document is reloaded partially (As I see reload icon in browser for some time).
I want to call my JavaScript function once the script got registered (Obviously when reload icon get stopped in the browser). But the function MyJavaScriptFunction got called while document is still reloading.
Using setTimeOut resolves the issue but I don't want to use it as page loading time is not fixed. Please help.
The code I am using is as follow:
function addScriptDynamically(src, callback) {
var s = document.createElement('script');
s.setAttribute('src', src);
s.onload = callback;
document.body.appendChild(s);
}
addScriptDynamically('URL Of JS File',function(){
MyJavaScriptFunction();
})
What I tried so far...
Option-1:
addScriptDynamically('URL Of JS File',function(){
$(document).ready(function(){
MyJavaScriptFunction();
});
})
Option-2:
addScriptDynamically('URL Of JS File',function(){
$(window).load(function(){
MyJavaScriptFunction();
});
})
jquery has a function for this purpose.
Using jquery
$(function () {
//write your function code here.
})
This function is called only when the content of the page are first loaded.
2)
Using Javascript
window.onload = function(){
//write your function code here.
}

How to replace $(document).ready function?

I got a problem and dont know how to fix it.
A have the following js script:
$(function () {
$.ajaxSetup({ cache: false });
var timer = window.setTimeout(function () {
$(".alert").fadeTo(1000).slideUp(1000, function () {
$(this).hide();
});
}, 3000);
$(document).on("click", "[data-hide]", function () {
if (timer != null) {
clearTimeout(timer);
$(this).closest("." + $(this).attr("data-hide")).hide();
}
});
});
<div class="well">
<h3>
<strong>#Model.Name</strong>
<span class="pull-right label label-primary">#Model.AverageRaiting.ToString("# stars")</span>
</h3>
<span class="lead">#Model.Description</span>
#Html.DialogFormLink("Update", Url.Action("UpdatePhoto", new {id = #Model.PhotoId}), "Update Photo", Url.Action("Photo"))
#Html.Action("InitializeAlerts")//When this action is executing the document was already ready (by the first time when full page was loading), so I have no chanse to catch any .alerts in js alert file after updating this partial for another one.
</div>
Sometimes I have a situation when document is ready ealier than I have any .alert classes im my partial view. So, how to rewrite the function to execute it after my partial view is updated with valid .alert?
You either need to wait around for $(",alert") to exist first, or you need to add your code inside the loading processing.
If you do not wish to couple your JS files tightly, you can broadcast a "panel loaded" event from the other script, which you catch at the document level.
e.g.
$.ajax({...}).done(function(loadedhtml){
$somepanel.html(loadedhtml);
$(document).trigger("panelloaded", $somepanel);
});
and listen for the generic "panel loaded" event in your main:
e.g.
$(document).on('panelloaded', function(panel){
// Do stuff here to the newly loaded panel
});
If you reload your Partial View i suppose the best thing is to place your code in .ajaxComplete() function.
It will be ready rigth after your ajax request done.

Passing reference to object javascript function

I have a function that gets called during a control update where 'This' is passed so the function knows what control is updating. I am also calling the function at page load to get initial values but sending document.getElementById() doesn't seem to work. What should I be passing here?
For example:
<script type="text/javascript">
window.onload = function () {
alert("Got to window.onload");
materialSelectionChange(document.getElementById('SquaresDropDownList'));
};
</script>
in the js file...
function materialSelectionChange(obj) {
alert("Got into function");
}
Also, it does fire the js function on change properly
EDIT
The problem seems to be the load time of the JS document. The function wasn't successfully being called at that point because apparently the JS file hadn't finished loading. Likely because of window.onload. It works if I move the function into the page rather than in the JS file. Is there a way I can add delay so I know the page and it's components are fully loaded?
You are not delegating for window load event, you are invoking it, also your missing quotes around the id:
window.onload = myFunction(document.getElementById(typeSelect));
Try wrapping it around:
window.onload = function() {
myFunction(document.getElementById('typeSelect')); //id in quotes
};
EDIT
You must take care of js file import, import must be first before invoking the function within:
<script src='your-script-file.js'></script>
<script type="text/javascript">
window.onload = function () {
materialSelectionChange(document.getElementById('SquaresDropDownList'));
};
</script>
<select id="typeSelect" onchange="myFunction(this)">
window.onload = function(){
myFunction.bind(document.getElementById('typeSelect'));
}
The problem seems to be the load time of the JS document. The function wasn't successfully being called at that point because apparently the JS file hadn't finished loading. It works if I move the function into the page rather than in the JS file. Is there a way I can add delay so I know the page and it's components are fully loaded?

Bootstrap Popover Not Working When Loaded With Ajax

When I load Bootstrap popver content with ajax, the popover is not showing.
Javascript:
var id = 1;
$.post("load.php?pageid",
{
pageid:id;
},
function(data,status){
document.getElementById("body").innerHTML=data;
});
HTML response:
hover for popover
<script>
$(function ()
{ $("#example").popover();
});
</script>
When I place the HTML response above directly in the <body id="body"></body> code, the popover works fine. I dont understand what is going wrong here.
The problem is that you're setting up the popover inside of the function $(). Rather than
$(function ()
{ $("#example").popover();
});
It should be just
$("#example").popover();
Or perhaps better
$(document).ajaxComplete(function() {
$("#example").popover();
});
The reason being that any function inside of $() is run when the document is first finished loading, when the "document ready" event is fired. When that code is pasted inside of the original HTML, it works because it's present when the document finishes loading.
When it's the response from an AJAX call, it won't run inside of $(), because the "document ready" event already fired some time ago.
with the help of jQuery you can initialize all things that needs to be initialized using
$(document).ajaxSuccess(function () {
$("[data-toggle=popover]").popover();
$("[data-toggle=tooltip]").tooltip();
// any other code
});
inspired from Olaf Dietsche answer
<script>$(function () { $('[data-toggle="tooltip"]').tooltip()});</script>
Add this at the end of whatever you are loading in with ajax. You should already have this somewhere to opt-in to the tooltip, but put it again to re-initialize the tooltip.

Categories