I am making a book, and use jQuery to change pages etc.
At the top I have an $(document).ready(function() that does different stuff when the page is loaded.
On the GUI page I got a "change page" button, and when this is pushed, the function turnPage() is called. This method contain some code pluss this:
$.mobile.changePage("#device"+window.device, {
transition: "slide",
reverse: false,
changeHash: true
});
My question is, when turnPage() is called, is also $(document).ready(function() called?
(Yes, I am new to this)
DOM ready event is an event that fires when the DOM is fully loaded except of images (<img>).
The event fires once for each page load. So:
If the turn page() function makes a redirect, the answer is Yes.
If the turn page() function only gets data with ajax request, the answer is No.
Important Update:
I found this in the official plugin website :
Important: Use pageInit(), not $(document).ready()
The first thing you learn in jQuery is to call code inside the $(document).ready() function so everything will execute as soon as the DOM is loaded. However, in jQuery Mobile, Ajax is used to load the contents of each page into the DOM as you navigate, and the DOM ready handler only executes for the first page. To execute code whenever a new page is loaded and created, you can bind to the pageinit event.
...
...
So turn page does an ajax request, so the final answer is No.
What is the ready event:
While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code. When using scripts that rely on the value of CSS style properties, it's important to reference external.
Related
I am trying some hands on with javascript core concepts and came across this interesting thought. When I use the native javascript and try executing some events on the document load as below I get an error:
document.addEventListener('load',function(){ //this doesn't alert doesn't get fired
alert("document load event listener fired!");
});
But if I change the above code as below it works:
window.addEventListener('load',function(){//this works alert gets fired
alert("Window load event listener fired!");
});
A possible explanation that comes to my mind is that the window the parent object in browser object model is loaded the first before anything else can be ready or accessed.
However in jQuery (something I have been more comfortable with) the syntax clearly starts with document as below:
$(document).ready(function() {
// some code here
});
I guess jQuery has an inbuilt wrapper around $(document) which actually takes care of firing the window load event before any further code mentioned inside it can be executed.
Is my understanding correct?
I have two questions on placing JS inside HTML. I can't find where these two points were answered here.
Questions are basically
Let's say I put Javascript in the head, and say the script tries to get some HTML element by ID, and register a click handler for it. Now since, the HTML has not been loaded yet (because the script is called in head), will this work?
On the other hand, if register a function in head which gets called when DOM is loaded, and inside that function I put code which registers handler for click on some button, then as I understand user has chance to click button but the handler will not be called because the whole DOM was not loaded yet (and that is where the button click handler is registered). Am I correct?
What is the solution and best way to put Javascript in HTML considering above two points?
Let's say I put Javascript in the head, and say the script tries to
get some HTML element by ID, and register a click handler for it. Now
since, the HTML has not been loaded yet (because the script is called
in head), will this work?
No, this won't work. Whenever <script> tag is seen, javascript is executed right away before going further with DOM building. (if javascript is external, it will wait to fetch it over network and execute it) It will act upon the current snapshot of DOM if the javascript is using DOM APIs like getElementById. When script tries to get the element by id, it tries to get it from DOM, (All DOM APIs acts on DOM) which is being built right now. As the element is not yet added to DOM (we are processing head) it won't be able to get the element. As it cannot get the element it will throw error if you try to access addEventListener or onclick of null.
On the other hand, if register a function in head which gets called
when DOM is loaded, and inside that function I put code which
registers handler for click on some button, then as I understand user
has chance to click button but the handler will not be called because
the whole DOM was not loaded yet (and that is where the button click
handler is registered). Am I correct?
Yes, you are correct. DOM load generalises the condition that all elements are added to the DOM and is ready for any operation on any element defined by HTML.
Also, window.load will be triggered only after DOM is loaded and all the external resources like images, videos are also loaded. Using it can delay the event attachments further.
What if I want to add event listener immediately?
If you want to immediately bind an event you can do it with inline scripts, just after the element although usually not a requirement and neither a good practice.
<p>whatever</p>
<button id="mybutton">Click me</button>
<script>
document.getElementById('mybutton').addEventListener(...
</script>
<p>rest of HTML</p>
This also opens another possibility, if you put your scripts at the end of HTML instead of head, it makes sure that all elements are added to the DOM and DOM is practically ready for any operations using DOM APIs. This was used widely when listening to DOM load event was not that easy. Although I can't find the correct reference, this was a recommendation by Doug Crockford.
we are usign knockout template for binding multiple pages. And On the main page we have a docuemnt.ready event
$(document).ready(function() { //some logic that makes use of the elements of child page. });.
Main page holds 3 child pages and as soon as the main page loads the ready event executes and result with error becuase child pages were not loaded by that time.
So it fires error that #inputbutton is null or not defined. Becuase at the time when ready event executed these child pages were loading.
So is there any way that we can hold the document.ready event of main to page to be fired after all the child page has been loaded completly? If we are able to do so then we will never get that error as every element will be available while the ready event fires.
Sorry cant disclose code because of some reasons
I found myself in a following situation. I need to somehow not include <div class="article-meta-social"></div> element and all its contents into my document.ready function. The reason is, it has links to apis from facebook, twitter, g+ etc... and Multiplied by several posts it results in a little delay before contents within document.ready function are fired off.
Therefore, what can I change in order for this
$(document).ready(function(){
});
To not wait until .article-meta-social and its contents are ready?
$(document).ready relies on the native DOMContentLoaded event, which does exactly what it says - fires when the entire DOM has been parsed. So to achieve what you want, insert the contents of .article-meta-social dynamically inside your ready handler. This way it won't hold up the main rendering of your page.
I know I can inject the script when the user clicks an element by creating a script element and injecting it on the page via document.appendChild. However, the script is listening for onload and onDOMContentReady (or their own home grown domReady event, not sure).
If I inject the script only when the user clicks an element, the callbacks for onload/onDOMContentReady will never fire because those events have already passed.
Any ideas? This 3rd party script pulls in all these other requests and it's not optimal for page loading.
EDIT: I read the question again...and if you are using something like jQuery, it will fire your handler function in any other document ready calls even if document ready has already been fired. It will just execute the function right away. If you are looking for a pure javascript way to do it, you need to take extra consideration to check to see if dom ready has already been fired, and fire your function yourself, otherwise attach it to the dom ready callback.
I don't see a problem with just doing something like this (with jquery for brevity):
// on document ready
$( function() {
// attach the click handler
$('#loadScript').click( function( e ) {
// on click, get the script
$.getScript('path/to/your/script.js', function() {
// your script is loaded, so what you need from here
// to handle this click event.
});
});
});
I think you are over thinking it a bit. You only need to worry about making it possible to load the script once the dom elements are ready. You could look at using something like require.js as well.