Script getting executed correctly once page is refreshed - jquery - javascript

In my webpage I have script like this :
<head>
<script src="scripts/effect.js"></script>
<script>
if (document.readyState == 'complete') {
doOnLoad();
}
$(window).bind("load", doOnLoad);
function doOnLoad() {
console.log("here..");
}
</script>
</head>
effect.js file contains script as shown below:
$( document ).ready(function(){
console.log("yes");
// here I've script for reading a text file using ajax and manipulating the result from text file
$.ajax({
// code goes here
console.log("ajax");
});
});
The problem is that when I run the page initially, I'm not getting the result. At that time I get console output as
yes
here..
ajax
But when I refresh the page again I am getting the result and console prints like :
yes
ajax
here..
How can I run window.load after the document.ready is completed.
Can anyone help me to fix this? Thanks in advance.

This is all about the timing of script execution. It sounds like the behaviour is changing once certain resources have been loaded and cached.
The first piece of code you have is a bit confusing:
if (document.readyState == 'complete') {
doOnLoad();
}
I'm not sure why you need this as well as the on load handler? It looks like that condition is never going to equal true anyway, as that code will run immediately before the document has finished loading. At the very least, I would put a console.log in this block, so I could determine what's triggering doOnLoad.
Try replacing the script on your page for just the following:
$(window).on("load", doOnLoad);
function doOnLoad() {
console.log("here..");
}

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

Execute jQuery after Other JS file Dynamically loads content

I'm working to modify some content which is dynamically loaded via another script(let's call is script #1) onto my site. Script #1 loads some markup and content and I've been using the setTimeout() function to call my script (Script #2) using a delay of a few seconds, in order to wait to be sure that Script #1 has executed and the content is present in the DOM.
My issue is that Script#1 has different loading times, based on the server load and can be slow or fast depending on these factors, and right now, playing it safe with setTimeout() I'm often left with a second or two where my scripts are still waiting to be fired and Script #1 has already loaded the content.
How can I execute my script as soon as Script#1 successfully loads it's dynamic content?
I've found this post which does seem to address the same issue but using the setInterval function as #Matt Ball has laid out there doesn't work at all for some reason. I'm using the code below where 'div.enrollment' is meant to find in the DOM which is dynamically loaded and execute..
jQuery(window).load(function ($)
{
var i = setInterval(function ()
{
if ($('div.enrollment').length)
{
clearInterval(i);
// safe to execute your code here
console.log("It's Loaded");
}
}, 100);
});
Any help on guidance on this would be greatly appreciated! Thanks for your time.
It seems that the healcode.js is doing a lot of stuff. There is a whole lot of markup added to the <healcode-widget> tag.
I would try to add another tag with an id inside and test for its existence:
<healcode-widget ....><div id="healCodeLoading"></div></healcode-widget>
Test in an interval for the existence of healCodeLoading inside <healcode-widget>: (Assuming jQuery)
var healCodeLoadingInterval = setInterval(function(){
var healCodeLoading = jQuery('healcode-widget #healCodeLoading');
if (healCodeLoading.length == 0) {
clearInterval(healCodeLoadingInterval);
// Everything should be loaded now, so you can do something here
}
}, 100);
healcode.js should replace everything inside <healcode-widget></healcode-widget> during init. So, if your <div>-element is no longer inside, the widget has loaded and initialized.
Hope that helps.
If you just want to load some markup and content and then run some script afterwards, you can use jQuery. You should use something like the following in script#1 to run a function in script#2
$.get( "ajax/test.html", function( data ) {
// Now you can do something with your data and run other script.
console.log("It's Loaded");
});
The function is called, after ajax/test.html is loaded.
Hope that helps

Define more than one onLoad in the same js file

How can i define more than one onload function (but different!)
in the same js file,
for ex,
file.js:
//---on load forpage1
$( document ).ready( handler ){
do something one
}
//---on load for page2
$( document ).ready( handler ){
do something else
}
and import it in both of the 2 pages:
for ex:
page1:
<!DOCTYPE>
<html>
<head>
<script type="text/javascript" src="file.js"></script>
</head>
page2:
<!DOCTYPE>
<html>
<head>
<script type="text/javascript" src="file.js"></script>
</head>
I'm assuming you ask this because you want to execute different code on the other page.
You could for example check location.href to see which page is currently being called.
More usual though is to use server side scripting to determine the current page and refer to the javascript accordingly.
Edit for an example:
$(function () {
var page = window.location.pathname;
if (page == "/index.html") {
// code here
}
else if (page == "/contact.html") {
// other code here
}
});
It depends what you're trying to achieve. If you want several functions to run when your page loads, the code in your post is almost correct:
$(document).ready(function() {
console.log("Function 1 running");
});
$(document).ready(function() {
console.log("Function 2 running");
}
You can also pre-define these functions if you want, and pass them to your $(document).ready() call:
function handler_1() {
console.log("Handler_1 is running");
}
function handler_2() {
console.log("Handler_2 is running");
}
$(document).ready(handler_1);
$(document).ready(handler_2);
And you can even use the jQuery shortcut $():
$(handler_1);
$(handler_2);
But if you want only one function to run when the page loads - depending on which page loaded - you'll need to take another approach. You could define all your code in script.js, and load init_page1.js from page 1, init_page2.js from page 2, etc. Those init files would call whichever setup function is appropriate for the page.
Alternatively, you could add a data attribute on your body tag indicating what page it's on, and have your $(document).ready() call the correct handler. Something like this:
$(document).ready(function() {
var page_type = $('body').data('page-type');
if (page_type == 'home') {
handler_1();
} else if (page_type == 'profile') {
handler_2();
}
});
And then, in your HTML file:
<body data-page-type="profile">
Possibly the neatest solution, though, is to have the callback functions determine whether they're relevant to the page. That way you can re-use them wherever you like. So your script would look something more like this:
function handler_1() { // Only for home page
if ($('body').data('page-type') != 'home') {
return;
}
console.log("I'm the handler_1 function");
}
function handler_2() { // Only for profile page
if ($('body').data('page-type') != 'profile') {
return;
}
}
$(handler_1);
$(handler_2);
Really, though, if you can avoid coding this into your JavaScript, you should. It's better to only include scripts that you know are required for that particular page to function.
In addition to $( document ).ready, which is called after the DOM is fully loaded for the current HTML file, including all images, the $(window).load is another method to detect DOM readiness that is not fired until all sub-elements, like iframes have been loaded and are available for use.
As to your original question, you can define as many $( document ).ready functions as you like; they are executed in the order they are found.
You can have multiple blocks of $(document).ready – but it won't solve your problem as they'll all be called once the DOM is loaded.
I'd recommend you to take a look at Paul Irish's DOM-based Routing.
Your question was very vague but I'm assuming you want multiple items to be called upon the page being loaded, in which the first example is.
document.ready(function(handler){
/*Do thing one*/
/*Do thing two*/
});
But if you mean for them to be called with different scenarios then you would use the handler passed in to check the status of the document and call a different item.
document.ready(function(handler){
if(handler==bar)
//Do thing one
else if(handler==foo)
//Do thing two
else
//Do thing three
});

More efficient way to wait for all images to load in jQuery

I'm using a mix of .ready() and .load() to execute my desired function.
jQuery(document).ready(function($) {
$("img").load(function() {
// Function goes here
});
});
As you can see, this waits for the DOM to be ready, then on each <img> load, it executes the code.
If I only had one image to load this would be simple.
But the problem is -- what if I have 10 images to be loaded? The function will be called 10 times due to each image loading one by one, and that's not a very efficient way to go about it just to achieve what I want.
So here's the question -- is there a more efficient way to wait for all images to load, then execute the function once?
You could do something like this to avoid having your function run multiple times.
jQuery(document).ready(function($) {
var nrOfImages = $("img").length;
$("img").load(function() {
if(--nrOfImages == 0)
{
// Function goes here
}
});
});
jQuery(window).load(function() {
alert("page finished loading now.");
});
jQuery(window).load(...) will be triggered after all content on the page has been loaded. This different from jQuery(document).load(...) which is triggered after the DOM has been loaded. I think this will solve your issue.
If anybody wants to know, my final result was this:
(function($) {
$(window).load(function(){
// Function goes here
});
})(jQuery);
that's because
jQuery(window).load(function($) {});
isn't a jQuery object, as referenced in this question:
Calling jQuery on (window).load and passing variable for 'No Conflict' code

AJAX that calls a "parent" function

I've seen a few questions like the one I'll ask but nothing identical. I have two html files, main and today. What I want to do is load today.html via AJAX into a child div in main.html. Sometime after load, I would like to call a function that resides in main.html from today.html
Within Main I have this function:
function drawCircle (size){
alert('DRAWING');
}
This AJAX load:
$("#leftofad").ajax({
url: ":Today.html?r="+genRand(),
type: 'GET',
success: function(data) { },
error: function() { alert('Failed!'); },
});
And this div:
<div id="leftofad"></div>
In Today.html I have
<script type="text/javascript">
$(document).ready(function(){
drawCircle (100);
});
</script>
The load is going well but Today.html doesnt seem to recognize the drawCircle function. I've tried several precursors including this., window., and parent..
I understand that I can use the callback method of the AJAX loader in jQuery but I don't necessarily want to call drawCircle when the load is complete. I may want to wait a bit or do it as a result of an action from the user. Is it possible to reference these functions from an AJAX-loaded div? If not, can I use an alternative method like events and listeners to fire the drawCircle function?
Since you will be loading JS into your page, try calling the function directly?
(The ready function won't run as the main page is already loaded)
Main.html
<script type="text/javascript">
function drawCircle(size) { alert("DRAWING" + size); }
$(function() {
$("#leftofad").load("Today.html?r="+genRand(), function() {
alert('loaded successfully!');
});
});
</script>
<div id="leftofad"></div>
Today.html
<script type="text/javascript">
drawCircle(100);
</script>
If this doesn't work, I strongly suspect that JavaScript returned in an AJAX call is not executed.
In this case, refer to: How to execute javascript inside a script tag returned by an ajax response
$("#leftofad").ajax is not proper.
jQuery's $.ajax function does not use a selector.
What you can use is load:
$("#leftofad").load("Today.html?r="+genRand(), function(){
alert('loaded successfully!');
});
Everyone here has some good answers, but I believe there is a knowledge gap and we are missing some information. If I were you, I would add an alert to the script in the Today.html file right before the drawCirle. Then I would run this page using IE or Chrome dev tools or Firebug in Firefox. When the alert is displayed you can put a breakpoint in the javascript code. Then check your global scope to try and locate drawCirle...
Sorry this is not an exact answer, but with javascript files you need to use debugging tools for this.
while there isn't really a document.ready function for a div, there is a hack that works just as if so:
create your returning data as a full html page:
<html>
<head>
<script type='text/javascript'>
$(document).ready( function () {
do-this;
to-that;
....
});
</script>
</head>
<body>
<%
your possible vbscript
%>
the rest of stuff to be loaded into that div
</body>
</html>
Then, you can have as many cascading div loading from different page loading and .... rinse and repeat ... forever .... EXPERIMENT with different DOCTYPE to see the different results.
EDIT:
Then, of course, you load the original MAIN with
$('#thedivid').load('url-of-the-html-returning-page');
Which, in turn, can have the VERY SAME call in the returning page document.ready as, for example; $('#thedivid-inthereturningdata-html-page').load('url-of-the-html-of-the-child-process-for-whaterver); .... and so on.
Go ahead, PLAY AROUND and make wonderful ajax based applications ....

Categories