I need some help. I'm a beginner on this. My javascript doesn't seem to be loading after a user clicks on a link_to and I think the issue might be compatibility with Turbolinks. Any one can help me on this? Below is my script. Thanks in advance!
$(document).ready(function() {
// executes when HTML-Document is loaded and DOM is ready
console.log("document is ready");
$(".navbar-nav").clone().prependTo("#off-canvas");
$(function() {
$(document).trigger("enhance");
});
// document ready
});
$(window).load(function() {
// executes when complete page is fully loaded, including all frames, objects and images
console.log("window is loaded");
// window load
});
This solution suggested in another question doesn't work for me at all;
$(document).on('turbolinks:load', function() {
try changing the line: (document).ready(function() {
to: $(document).on('turbolinks:load', function() {
if you have already tried that and it does not work, you may need to reinitialize/load the js in the final js.erb file.
You can do this a few ways. Here is one:
Attach your javascript to the window so that it is globally available.
Call that function in your js.erb like this: Global.some_js_function();
Related
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!");
});
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!");
});
I have a custom js file in app/assets/javascripts.
This is the js file:
//app/assets/javascripts/contacts.js
//$(document).ready(function() { //I've already tried with this method
$(window).load(function() {
alert("foo bar")
});
I require the file contacts.js file in the application.js file.
If I inspect the html page I see the js file loaded correctly, but the message is not shown.
If I reload the page (by pressing f5), the message is correctly show.
When the page is loaded the javascript is loaded (I can see it in source html code in the browser) but not executed.
Can you help me?
SOLUTION:
Rails 4: how to use $(document).ready() with turbo-links
$(document).ready(function() { } # Not working with turbo-links
From
Turbolinks overrides the normal page loading process, the event that
this relies on will not be fired. If you have code that looks like
this, you must change your code to do this instead:
$(document).on('ready page:load', function () {
// you code here
});
Another question
With Turbolinks version 5 (starting from Rails 5) you need to use:
$(document).on("turbolinks:load", function () {
// YOUR CODE
});
I'd like to conditionally load a set of javascript functions (which involve jQuery) on a given page.
The situation is that our site has a bunch of stuff that happens on $(document).ready (mostly fancy menu setup and a couple of CSS class manipulations), but one or two pages need more setup. It's enough code (and specific enough) that I don't want to just toss it into the main file, but rather just load it on those specific pages.
It seems that I can't do this by just loading a new file specific.js into those pages that contains
(function () {
$(something).click(function () { Stuff(happens); });
something(Else);
...
} ());
In the above example, something(Else); works fine, but .click and .bind don't seem to do anything. What I ended up doing is
function specificStuff () {
$(something).click(function () { Stuff(happens); });
something(Else);
...
};
and adding if(specificStuff) specificStuff(); to the main js file. It works, but it seems like there should be a better way of accomplishing this (ideally one that would keep all the changes in specific.js and not touch the general settings).
Is there a canonical way of conditionally loading js code to run in document.ready?
You can call $(document).ready(); multiple times in a web page/script file. Just wrap your jquery bindings as such in your specific.js file:
$(document).ready(function(){
$(something).click(function () { Stuff(happens); });
something(Else);});
You can load the page specific Javascript in the html of those pages, each script with its own document.ready function.
try removing the () when passing a function to document.ready:
(function () {
$(something).click(function () { Stuff(happens); });
something(Else);
...
} **()**);
with the (), it will execute right away and not wait for the document to be ready.
You can call the jquery document ready function as many times as you need. I think your issue is with how you've set up your function. If you're trying to call the ready function, it should be like this:
$(function () {
$(something).click(function () { Stuff(happens); });
something(Else);
...
});
Also, if the something elements are created by your main.js file, you should include it before your specific.js file.
the program needs invoke a function after all code, including HTML, javascript, CSS, etc., is loaded? Can javascript do it?
for JavaScript
window.onload = function(){
//your code
};
for JQuery
$(document).ready(function(){
//your code
});
window.onload will fire after all images, frames and objects have finished loading on the page. Your question isn't clear enough on whether or not you want the script to wait for those, but if you don't then you need a "document ready" solution.
Firstly, many (all?) DOM-based Javascript frameworks provide this functionality, cross browser in the form of an event. jQuery example:
$(document).ready(function() {
alert("DOM is ready");
});
If you want to do it without the framework, it gets a little more awkward. Most browsers (coughnotIE) provide a DOMContentLoaded event:
if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', function () {
alert("DOM is ready");
}, false);
}
For IE's part, the defer attribute on a script tag will do the job. You can use conditional comments to make sure only IE parses the script:
<!--[if IE]
<script type="text/javascript" defer>
alert("DOM is ready");
</script>
<![endif]-->
If you're using the jQuery library, you simply do this:
$(document).ready(function() {
// The code you need to have executed after loading the page
});
window.onload = function() {
// Your code here
};
What have you tried?
You can use <body onload="doStuff()">, or you can use window.onload in your script. Check this out.
The jQuery $(document).ready(...) method is triggered when the dom is loaded and can be manipulated and before all scripts, images, etc. are loaded.
The window.onload event will fire when everything that has been requested has completed loading.