So, I have a div (id="content") where I'm loading various other HTML I get from AJAX requests. I want to be able to tell when they have loaded successfully, but the load event does not seem to work with append().
I have this simplified example to illustrate the situation (in the real case, the listeners for the 'load' event are registered in different files which get loaded in the section of the script)
<html>
<head>
<script
type="text/javascript"
src="http://code.jquery.com/jquery-latest.min.js">
</script>
</head>
<body>
<div id="content"><div>
<script type="text/javascript">
$(document).ready( function () {
// this does not seem to work
$("#myDiv").on('load', function () {
console.log("myDiv loaded");
});
// neither does this
$("#content").on('load', "#myDiv", function () {
console.log("myDiv loaded by delegation");
});
// the content to append will come from the network
$("#content").append($("<div id='myDiv'>myDiv</div>"));
});
</script>
</body>
</html>
Of course, in the real case things are more complex (the loaded data can be anything) so these are not valid options:
having a function called after the div has loaded
having a function embedded in the loaded code (the code is generated from template files)
If you get the data from Ajax requests you should actually use the Ajax done() function. Since the call is async, you wont be able to listen to the changes in the div. Another solution would be to add a body delegate on the div and make it listen to the change event.
$("body").delegate("mydividentifier", "change", function(f){});
$.ajax().done(function(f){});
Related
My index.html include two javascript codes which are plugin.js and main.js(main include after plugin),
I want to make plugin.js as a reusable plugin, like checking if the index.html file has any elements which have click-me class attribute, if index.html has this kind of elements, then set every this kind of elements an eventListener.
I want my window.onload function ALWAYS in main.js rather than plugin.js, but in this case I cant' get DOM object by className in plugin.js, I also don't want to call any function of plugin.js in main.js.
Does anyone ahs any idea?
You can just include the scripts after the body.
<body>
</body>
<!-- add your scripts here -->
Then you don't need to check if the document is ready anymore, this has the drawback of only starting the download after the page is fully rendered.
Another possibility is using defer
<script type="text/javascript" src="plugin.js" defer></script>
<script type="text/javascript" src="main.js" defer></script>
This way scripts are downloaded as soon as possible but are executed only after the page is ready, and in order.
A more detailed answer here
Well, you should properly use onload as an event listener:
window.addEventListener("load", function() {
});
This can be added as many times as you wish, both in main.js and plugin.js.
Additionally, it's better to use DOMContentLoaded event, because it doesn't wait on loading images. That's really important, if you rely on window.onload, just one pending image can make your page useless for first 10 seconds of the visit. It's used like this:
document.addEventListener("DOMContentLoaded", function(event) {
console.log("DOM fully loaded and parsed");
});
It has compatibility issues however, so I recommend using some library.
Oh and last thing - don't link your scripts before body unless needed. They block parsing of the page.
Why don't you just check if the clicked element have the click-me class from the root? It makes you declare only one listener on the body.
function listener(event) {
if(event.target.classList.contains("click-me")) {
// Do something
}
}
document.body.addEventListener("click", listener, true);
I have Jquery function that executes AJAX query to server.
How can I call this after load page in the specified url page? May I bind this to element HTML, I mean:
<div id="graph" onload="function()"></div>
jQuery handles the HTML file with a variable called document.
Document has two popular event states
load when the page has been loaded
ready when the page has been loaded and all other decorations to the HTML have been applied.
jQuery provides hooks for these states.
To run javascript code after each of the events listed above, you have to put the function within the appropriate event scope.
For loading, this would be…
$(document).load(function() {
// javascript code you want to execute
})
After the page has been ready, but not yet rendered, you can apply some other javascript code using
$(document).ready(function() {
// javascript code you want to execute
})
One way using jQuery:
$(document).ready( function() {
//do whatever you need, you can check if some element exists and then, call your function
if($("#graph").length > 0)
callfunction();
});
No jQuery, only vanilla js:
window.onload = function() {
if(document.getElementById("graph"))
callfunction();
}
I am new to javascript so I make this thread. I read some post. In this post is the function inside or outside of the document ready. If it is declare outside the document can I re-use / call it in another JScript?.
As my title what should be the contain inside of a document ready?.
$(document).ready is an event which fires up when document is ready.
Suppose you have placed your jQuery code in head section and trying to access a dom element (an anchor, an img etc), you will not be able to access it because html is interpreted from top to bottom and your html elements are not present when your jQuery code runs.
To overcome this problem, we place every jQuery/javascript code (which uses DOM) inside $(document).ready function which gets called when all the dom elements can be accessed.
If you place your jQuery code at the bottom (after all dom elements, just before ) , there is no need for $(document).ready
See the example, which alert calls first that will give you an idea what should be inside the ready.
alert("Without Ready");
$(document).ready(function(){
alert("With Ready");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
.ready makes sure your DOM is ready and good to go for binding, so putting all your functions inside there like the events functions would only be bootstrap at ready state of the document. Normal functions( with name i.e non anonymous functions) can be declared outside the document.ready so you can re-use it somewhere else. since those functions are called from the document.ready events or jquery code to be used.
See more about document.ready here. check the snippet below for a brief example layouting
/**
Global function here, which is not called or bind on page load
*/
function alertWindow(message){
alert ("Window is loaded here with Message: "+message);
$("#console").text(message);
}
$(document).ready(function(){
$("#showBtn").click(function(event){
var ourMessage = $("#message").val();
alertWindow(ourMessage);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="message" placeholder="Enter Message" >
<br>
<button id="showBtn">Show Message</button>
<p>
<h3>Console Here</h3>
<div id="console"></div>
</p>
when we use document.ready all the listeners and all the functions inside the document ready will work only after the page load completed.
So for example if you added any listener to a button and that perform some change in your page then better to write it inside the document.ready.
First things first - In JavaScript a function defines the scope of the code it contains, so if you want to share it you need to define it in a location that your other code can see.
You also don't need to define functions inside the document ready function, you could just define outside of the ready() callback. Eg,
$(document).ready(function(){
$('button').click(function(){
somefunc();
});
});
function somefunc()
{
alert('yes');
}
$(document).ready(function(){
// do something else
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Hope this help..
The ready event occurs when the DOM (document object model) has been loaded.
Because this event occurs after the document is ready, it is a good place to have all other jQuery events and functions. Like in the example above.
source : http://www.w3schools.com/jquery/event_ready.asp
For example: if DOM is not fully loaded and our JS code is trying to access unloaded DOM. We will get Javascript error. To avoid this we need to give some time for loading document. To achieve this, We have a callback function for DOM loaded $(document).ready() or $(function)
We can have functions out side ready and those we can access for other JS also. It is always better to write Jquery add event and other Jquery related code inside ready method.
Refers from here:
A page can't be manipulated safely until the document is "ready."
jQuery detects this state of readiness for you. Code included inside
$(document).ready() will only run once the page Document Object
Model (DOM) is ready for JavaScript code to execute. Code included
inside $(window ).load(function() { ... }) will run once the entire
page (images or iframes), not just the DOM, is ready.
Since usually we've used jQuery to selecting and/or manipulating the DOM, so the best way to that is after the DOM is fully loaded. For those reason, so we need an event to watch the DOM ready state. This method give us flexibility where we'll write our javascript code, either on <head> nor at the end of <body>.
See my snippet samples below:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
// this will not work properly
$('div').html('Hello World!!!');
</script>
</head>
<body>
<div>Hi brother!!</div>
</body>
</html>
Above script will not work properly since the script was executed
before the DOM loaded properly. So, the jquery can not find the
element with div tag.
To make the script running smooth, we need to add additional event listener from jquery named $(document).ready() as you can see at snippet below.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
// this will work properly
$(document).ready(function() {
$('div').html('Hello World!!!');
});
</script>
</head>
<body>
<div>Hi brother!!!</div>
</body>
</html>
But, how if we don't want to add ready method? We still can do that, if we write the script below required DOM, see below snippet for example:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div></div>
<script>
// this will not work properly
$('div').html('Hello World!!!');
</script>
</body>
</html>
UPDATE :
Refers from OP comment below:
In your reference I read use the shorthand $() for $( document
).ready() so I can use like $() for document.ready?
YES, you can use that shorthand, see my snippet below:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
// this will work properly
$(function() {
$('div').html('Hello World!!!');
});
</script>
</head>
<body>
<div>Hi brother!!!</div>
</body>
</html>
In order to optimize the load of my document, I use to load jQuery async like that
<script async type="text/javascript" src="js/jquery-1.12.3.min.js"></script>
Then I call a script using jQuery :
<script type="text/javascript">
jQuery(document).ready(function() {
App.init();
OwlCarousel.initOwlCarousel();
FancyBox.initFancybox();
StyleSwitcher.initStyleSwitcher();
});
</script>
It returns me that jquery is not defined.
I don't know what should I use, I though that .readyfunction would wait until all document is loaded before calling it.
The same for Bootstrap library, It tells me that jQuery is not defined.
I've tried to ask the script to be loaded at the end, but it still does not work properly.
Since jquery script is loaded asynchronously, jquery is not loaded on the moment your script is executing. So you need to wait for it to load by subscribing on load event like this:
<script async id="jquery" type="text/javascript" src="https://code.jquery.com/jquery-2.2.3.js"></script>
Then listen for a load event on this element
<script type="text/javascript">
document.getElementById('jquery').addEventListener('load', function () {
App.init();
OwlCarousel.initOwlCarousel();
FancyBox.initFancybox();
StyleSwitcher.initStyleSwitcher();
});
</script>
But I don't know why someone wants to do things like this.
To optimize page loading speed it is better to put all you javascript at the end of the body, so content will be loaded first, and scripts won't delay page rendering event if it's synchronously loaded.
Edit: I agree with comment and consider previous paragraph not the best way of loading jQuery to the page
Question Script Tag - async & defer has good answer to your problem.
In a nutshell you cannot load jQuery, or other library, asyncronously when some other script depends on it without some additional asyncronous handling for executing the scripts depending on the library.
That is my solution:
<script async type="text/javascript" src="path_to_jquery" id="jquery_script_tag">
</script>
<script>
if ( !('jQuery' in window) )
{
window.jQueryQueue = [];
//define temporary jQuery function
window.jQuery = function(){
//just save function parameters to queue
jQueryQueue.push( arguments );
}
document.getElementById('jquery_script_tag').addEventListener('load', function(){
//call jQuery with parameters saved in queue, after it loaded
for ( var i in jQueryQueue )
jQuery.apply( document, jQueryQueue[i] );
});
}
</script>
This code defines a temporary jQuery function if it is yet not defined. The function saves all jQuery function calls to queue while the real jQuery has not yet loaded (instead of calling undefined jQuery function). And when jQuery has loaded, it calls the jQuery functions in the queue with the same parameters as called before.
jQuery, and all components that depend on jQuery (including Bootstrap), depend on hooking the DOMContentLoaded event to set up events.
This means jQuery (and anything that uses $(function() {...})) must be downloaded before DOMContentLoaded fires, or it never hooks up its events.
In turn, that means <script async ... will be unreliable, breaking whenever jQuery takes longer to download than the page content does.
Unfortunately <script defer ... doesn't work either thanks to jQuery trying to fire as soon as the document.readyState === "interactive".
You can load content and then load jQuery by putting the <script> at the end of the <body> but this will result in a noticeable pause between the page appearing and any of the jQuery firing - users won't be able to click on anything, visual components won't appear, and so on.
This way works just fine:
<script charset="utf-8" type="text/javascript">
var intervalID = window.setInterval(function(){
if(window.jQuery){
clearInterval(intervalID);
console.log('Loaded');
/* Your code here */
}
},1000);
</script>
You Used Async Loading When You Try Access Jquery It Not Loaded By Browser You Can Access Jquery After Page Loading Is Complete .
Load Jquery Normally To Fix Your Problem .
Is there anyway to check if page is fully loaded.Something like this http://msdn.microsoft.com/en-us/library/system.web.ui.page.loadcomplete.aspx but for JAVA.
If you intend to execute logic on the client side when the page is loaded, you might be interested in the Javascript onload event.
Or, even better, consider using jQuery and use the ready() function to execute your logic.
Just a short example using jQuery:
$(document).ready(function() {
alert("The document, including all assets such as images, has been completely received");
});
Not directly in java, since it is probably not running in the browser, but you can do it with javascript
<html>
<head>
<title>Test Page</title>
<script type="text/javascript">var myFunc = function() {
alert("The page is fully loaded!");
};
window.onload = myFunc;
</script>
</head>
you can use the normal onload()
<body onload="yourFunctionHere()">
or the JQuery version
$(document).ready(function() {
yourFunctionHere();
});
1. JQuery will help you:
there is $(document).ready() which tell you that the browser is loaded.
Example:
$(document).ready(function(){
$("button").click(function(){
$("p").slideToggle();
});
});
The ready event occurs when the DOM (document object model) has been loaded, and the page has been fully loaded (including images).
Because this event occurs after the document is ready, it is a good place to have all other jQuery events and functions. Like in the example above.
2.Window onload is another JavaScript approach:
window.onload=function(){SomeJavaScriptCode};
The onload event occurs when an object has been loaded.
onload is most often used within the element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.).
Note: The main difference is that document.ready() event gets called as soon as your DOM is loaded. It does not wait for the contents to get loaded fully, while window.onload will wait until all your contents are loaded fully.
We can have more than one document.ready() function in a page where we can have only one onload function.
Not in Java, no.
You'll need Javascript:
<script>
window.onload = function() {
alert('Loading Complete!');
}
</script>