I am a newbie on javascript and was implementing a loader in the project..
I have used the below code for the implementation of loader but it is not working:-
var url = "http://localhost:3500/#!/Movies";
<script>
$(function(){ //Loader implementation
if (location.href==url){
$(window).ready(function(){
$('#loadIndicator1').fadeOut(1000);
return false;
});
}
});
</script>
I am calling the loadindicator in the code as:-
<ul>
<li id="loadIndicator1" style="position:absolute ;top:50%;left:50%;z-index:99999;"></li>
</ul>
I am not very sure why this is giving an issue.I am using jquery-1.8.3.min.js and jqueryui-1.10.2.js
Also when I hover on location..I get unresolved variable location.Please help me with this.
use
if (window.location.href==url)
instead of
if (location.href==url)
var url = "http://localhost:3500/#!/Movies";
$(function(){
if (location.href==url){
$(window).load(function(){
$('#loadIndicator1').fadeIn(1000);
});
}
});
this will show your loader once the webpage is fully downloaded
use $('#loadIndicator1').fadeOut(1000); to hide the loader once the content is loaded.
Ignoring window ready, using only document ready
$(function() {
if (window.location.href === url){
// $(window).ready(function(){
$('#loadIndicator1').fadeOut(1000);
return false;
// });
}
});
You should remove the part I have commented out. The problem is, you attached an event handler to document ready, and if your are on a specific URL, you attach an event handler to window ready, but that event was already fired, and it won't be fired again.
Using window load after document ready
Another possible solution:
$(function() {
if (window.location.href === url){
$(window).load(function(){
$('#loadIndicator1').fadeOut(1000);
return false;
});
}
});
The window load event fires later, than document ready - though this should be tested.
Ignoring document ready, using only window load
Third time is a charm, another solution which may be the best, simply ignore the document ready event, and only use the window load:
$(window).load(function () {
if (window.location.href === url) {
$('#loadIndicator1').fadeOut(1000);
return false;
}
});
This case though the loader only appears if everything is loaded on the page, so maybe this is not what you want -- in this case use the first option.
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!");
});
This question comes from
Actually, I was able to find a clue and this is what I found. I have a js file:
$(document).ready(function() {
var myIdElement = $("#some_id");
//............
$.ajax({
url: getFullUrl(myIdElement.val())
})
//..........
So when I come to this page from the another page by a link (html link) then myIdElement is undefined. However, when I reload the page it starts having a proper value. I use turbolinks.
How do I get it to work in all situations?
$(document).ready does not always fire in turbolink. Use page:load event, instead. On the first page, it fires ready event, but on subsequent pages, document has always been ready, hence no document ready event is fired. So, it fires page:load to help us.
function ready () {
// Your code goes here...
}
jQuery(document).ready(ready);
jQuery(document).on('page:load', ready);
Try this:
(function($) {
$(document).ready(function() {
var myIdElement = $("#some_id");
//............
$.ajax({
url: getFullUrl(myIdElement.val())
})
//..........
})(jQuery);
Strange situation:
I am building a menu bar using jQuery and CSS.
In my JavaScript file, I have an on-ready function like so:
$(document).ready(function(e) {
mark_active_menu();
}
and...
function mark_active_menu() {
var elementWidth = $("nav li").width();
alert(elementWidth);
}
For some reason, even BEFORE all the document finish loading, I'm getting the alert message with an incorrect width. Only when I release the message, the rest of the document loads and I'm getting the right width as it should be.
Why my function is being called BEFORE all the document finish loading?
Is there a way to load the function only AFTER a certain element done loading (Example: the nav element)?
You can use window.load, it will be triggered after all the resource have completed loading.
$(window).load(function(e) {
mark_active_menu();
});
The load event fires at the end of the document loading process. At
this point, all of the objects in the document are in the DOM, and all
the images and sub-frames have finished loading, Reference
All the current solutions are just treating symptoms of the main problem. If you want your handler to execute after all your ajax loads, then you may use a promise.
var ajax1 = $.ajax();
var ajax2 = $.ajax();
jQuery(function($) {
$.when.apply($, [ajax1, ajax2]).done(function() {
// your code here
});
});
Try on the window load event :
$(window).load(function() {
//Stuff here
});
To be sure, Try window load
$(window).load(function(e) {
mark_active_menu();
}
Before(sometimes, doesn't load absolutely at the beginning, a few milliseconds after(0-200ms about)):
$(document).ready(function(){
$('body').hide(0);
});
After:
$(window).load(function(){
$('body').delay(500).show(0);
});
In my situation of work with AJAX and HTML. I have the same problem with functions $(document).ready() and $(window).load(). I solved this problem by adding handler of my event (that should work at HTML DOC), to the jQuery function that runs right after AJAX reguest was finished. Read this: "
jQuery.post()" (third parameter in the function).
In my code it looks like this:
var RequestRootFolderContent = function(){
$.post(
'PHP/IncludeFiles/FolderContent.inc.php',
function(data){
$('[class~="folder-content"]').html(data);
//Here what you need
$('[class~="file"]').dblclick(function(){
alert("Double click");
});
}
)
}
After the request, the new elements created are not recognized by the event handlers in my jQuery code.
Is there a way to reload the file to re-register these events?
I'm assuming that you mean that events you've registered for elements that have been replaced by with the results of your ajax requests aren't firing?
Use .live() (see http://api.jquery.com/live/) to register the events against elements that the match the selector (including the new DOM elements created from the results of the ajax), rather than the results of the selector when the event handlers were first, which will be destroyed when they are replaced.
e.g.
replace
$('div.someClass').click(function(e){
//do stuff
});
with
$('div.someClass').live('click', function(e){
//do stuff
});
Important:
While I've recommended using .live() this is for clarity as its syntax is similar to .bind(), you should use .on() if possible. See links in #jbabey's comment for important information.
This question was about binding event handler on DOM element created after the loading of the page. For instance, if after a request ajax you create a new <div> bloc and want to catch the onClick event.
//This will work for element that are present at the page loading
$('div.someClass').click(function(e){
//do stuff
});
// This will work for dynamically created element but is deprecated since jquery 1.7
$('div.someClass').live('click', function(e){
//do stuff
});
// This will work for dynamically created element
$('body').on('click', 'div.someClass', function(e){
//do stuff
});
You would find the documentation here: http://api.jquery.com/on/
This codes works perfect for me..
$("head script").each(function(){
var oldScript = this.getAttribute("src");
$(this).remove();
var newScript;
newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = oldScript;
document.getElementsByTagName("head")[0].appendChild(newScript);
});
It removes the old script tag and make a new one with the same src (reloading it).
To increase the website performance and reduce the total file’s size return, you may consider to load JavaSript (.js) file when it’s required. In jQuery, you can use the $.getScript function to load a JavaScript file at runtime or on demand.
For example,
$("#load").click(function(){
$.getScript('helloworld.js', function() {
$("#content").html('Javascript is loaded successful!');
});
});
when a button with an Id of “load” is clicked, it will load the “helloworld.js” JavaScript file dynamically.
Try it yourself
In this example, when you clicked on the load button, it will load the “js-example/helloworld.js” at runtime, which contains a “sayhello()” function.
<html>
<head>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
</head>
<body>
<h1>Load Javascript dynamically with jQuery</h1>
<div id="content"></div>
<br/>
<button id="load">Load JavaScript</button>
<button id="sayHello">Say Hello</button>
<script type="text/javascript">
$("#load").click(function(){
$.getScript('js-example/helloworld.js', function() {
$("#content").html('
Javascript is loaded successful! sayHello() function is loaded!
');
});
});
$("#sayHello").click(function(){
sayHello();
});
</script>
</body>
</html>
In your request callback, call a function that acts on your newly appended or created blocks.
$.ajax({
success: function(data) {
$('body').append(data);
//do your javascript here to act on new blocks
}
});
simple way to solve this problem
$(document).ready(function(){
$('body').on('click','.someClass',function(){
//do your javascript here..
});
});
You can also attach the click handlers to the body so that they never get destroyed in the first place.
$('body').on('click', 'a', function(event) {
event.preventDefault();
event.stopPropagation();
// some stuff
})
var scripts = document.getElementsByTagName("script");
for (var i=0;i<scripts.length;i++) {
if (scripts[i].src)
if(scripts[i].src.indexOf('nameofyourfile') > -1 )
var yourfile = scripts[i].src;
}
jQuery.get(yourfile, function(data){
if(data){
try {
eval(data);
} catch (e) {
alert(e.message);
}
}
});
You can try loadscript plugin for loading the javascript file.
forexample
$("#load").click(function(){
$.loadScript('path/example.js');
});
or
$.ajax({
success: function(data) {
$.loadScript('path/example.js');
}
});
http://marcbuils.github.io/jquery.loadscript/
What do you mean not recognized by jQuery?
jQuery walks the DOM each time you make a request, so they should be visible. Attached events however will NOT be.
What isn't visible exactly?
P.S.: Reloading JavaScript is possible, but highly discouraged!