Javascript not working on page refresh - javascript

So I have this block of code:
$(document).ready(function() {
planSelectionForm.init($("form#new_account"));
});
And when I link to this page it works as expected. But when I refresh from the browser it doesn't get triggered. This seems like a common problem. Just for the record I'm using turbolinks. Any help on why this is happening would be great!

The only solution I could find after getting this problem was wrapping my script with:
document.addEventListener("turbolinks:load", function() {
planSelectionForm.init($("form#new_account"));
});

Wrap your .onready() functions into a function called initialize. The point, is to seperate the event-driven function calls such that the event driven function call calls a global function.
In there, add to your body or another element that supports onload.
$(document).ready(function() {
initialize();
});
function initialize()
{
}
<body onload="initialize(); return;"> </body>
Also, for Caleb, in my experiance, I believe jQuery ready events only get executed on either a fresh load, or a ctrl+f5 cache reload.

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

jquery script to run on loaded content

I'm having trouble getting my scripts to run for content that has been loaded onto the page via .load().
In particular, how do you make a script that should run on .ready work?
Sample script:
$(document).ready(function() {
$('.content').fadeIn();
});
-- It runs fine on standard pages, but won't work for .load() sections.
You have no slow variable defined. It should be a string, so:
$(document).ready(function() {
$('.content').fadeIn('slow');
});
async functions come with a callback, use that to perform operations on the content once the load is complete:
$("yourElementSelector").load("url", function() {
//load is completed, do work here
});
Your event will only run when the page is first loaded and ready, any other event such as .load() will need additional event handlers attached.

Click button on load event

I have the following javascript -
function onLoad() {
if (!(document.applets && document.VLVChart && document.VLVChart.isActive())) {
setTimeout('onLoad()', 200);
return;
}
objChart = document.VLVChart;
PollEvent();
}
function fan() {
objChart.reorganize();
}
And then when the HTML page is loaded -
<body onLoad="onLoad()">
and have a button within the HTML that execute the fan() function -
<input type='button' value='Fan' onClick='fan();'>
Is it possible for me to activate the fan() function within the onload event so that a user does ont have to click the button?
EDIT
After trying the provided answers, on debugging the code breaks on the line -
objChart.reorganize();
Within the fan() function with the error -
SCRIPT5007: Unable to get value of the property 'reorganize': object is null or undefined
This is odd as when I manually click the button on the page, the function works fine.
Solution
After much head scratching I have realised that I was trying to load the fan() function before the page (and more specifically the objChart) had fully loaded. Hence why adding the function in the onLoad event was not working. I added a setTimeout -
function Fan()
{
setTimeout(function(){objChart.reorganize();},3000);
}
<body onload='onLoad(); fan();'>...
However inline JS is best avoided and you would do well to begin looking into centralised event management. There are various advantages to this.
An answer I wrote yesterday to another question outlines why this is. Something like jQuery makes this trivial if it's new for you.
$(function() {
$('body').on('load', function() {
onLoad();
fan();
});
});
Reading your question I assume you didn't even have tried. Just call that function from within your onLoad()-function:
function onLoad()
{
fan();
/* … */
}
Yes.
You can use <body onload='onLoad(); fan();'> as Utkanos suggests.
If you use jQuery, you can also stick a script in the head containing:
$(function(){
...
});
The jQuery function actually fires earlier, as is explained here.

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 ....

How can I tell when all images on a page are loaded using jQuery?

I’m using jQuery for my project. $(function(){...}) fires the function “when the DOM is ready” — this doesn’t say that all images are loaded, right?
Is there an event that gets fired when every image is loaded too?
I guess you mean
http://api.jquery.com/ready/
versus
http://api.jquery.com/load-event/
Example: Run a function when the page is fully loaded including graphics.
$(window).load(function () {
// run code
});
without jQuery:
window.onload=function() {
alert(document.images.length);
}
You can check on load event of image tag. This will get fired when image loading completes.
$("img").load(function(){
// your code
});
window.onload will solve this, I wrote about this there: http://amrelgarhy.com/blog/how-to-tell-when-images-have-loaded/

Categories