Is it OK to mix window.onload and $(function(){}); of jQuery in the same script?
<script type="text/javascript">
this.onload = function () {
// do something
}
$(function () {
//do something
});
</script>
it is perfectly acceptable to do what you asked:
// check when DOM is ready
$(function(){
// place code here
console.log('DOM ready');
});
// check when all images, links and assets have been loaded
window.load = function(){
// place code here
console.log('window loaded');
};
also you can do this to make sure the DOM is ready before checking the load event
// check when DOM is ready
$(function(){
// check when all images, links and assets have been loaded
$(window).on('load',function(){
// place code here
console.log('window loaded');
});
console.log('DOM ready');
});
or with native javascript for window.load event
// check when DOM is ready
$(function(){
// check when all images, links and assets have been loaded
window.load = function(){
// place code here
console.log('window loaded');
};
console.log('DOM ready');
});
Even the JQuery API docs ready() say its ok: http://api.jquery.com/ready/
You can do this to make sure the DOM is ready before checking the window.load event. It can be placed outside yes, but sometimes due to different browser inconsistencies, and other scripts loading in.
Its perfectly acceptable for the window.load event to go inside the ready function to guarantee the window.load event fires after the DOM is ready, and not before.
Since the jQuery ready function, in some instances, will sometimes fire before all images have been loaded. when inside the ready() event, the window.load event will fire immediately once the ready handler is run if all images, links, etc have loaded.
You're referring to window.onload = function () { }; Which will be triggered after all images have been loaded, etc.
$(function () { }); or $(document).ready(function () { }); is triggered after the DOM has been successfully created, and thus, when you can be certain you can select any/specific elements.
This will work because $(function () { // ... }) is the short form of $(document).ready() and this event fires immediately after DOM is parsed/ready but window.onload fires after all resources have been loaded, including all images, so $(function () { // ... }) will fire once at first and then the onload event will fire again.
$(function () {
console.log('reday event'); // this will fire at first
});
this.onload = function () {
console.log('load event'); // this/second will fire after "ready" event
}
Also, remember, window.onload is equivalent of jQuery's load event, i.e. $( window ).load(function() { // ... }).
Check this example, (both events fire one after another, ready then onload).
I am not sure why you would as they do basically the same thing, so there should be no issue.
Related
I am writing a chrome extension, that has this content_script. I have written 3 functions to be triggered by 2 respective events - The double Click and Load function.
The Double Click event executes the function written for it, but, the load function or onload function are not executing their respective functions.
$("*").dblclick(function(){
alert("Double Click");
})
document.addEventListener ("onload", myMain, false);
function myMain (evt) {
alert("On Load");
}
document.addEventListener ("load", myMain, false);
function myMain (evt) {
alert("Load");
}
Using jQuery, here is my understanding of desired events :
$(window).on('load', function() {
alert('Loaded');
});
$(document).ready(function() {
alert('Ready');
});
$(window).on('dblclick', function() {
alert('Double click');
});
The difference between event 'load' and 'ready' is :
'Load' is triggered when your page is completely loaded (images,
charts ...).
'Ready' is triggered when your page script's is safe to manipulate.
Just check jQuery documentation for event on document loading : https://api.jquery.com/category/events/document-loading/
There is no event to trigger a document 'onload'.
You can use the DOMContentLoaded event in JS to achieve this. Like this:
window.addEventListener('DOMContentLoaded', myMain);
function myMain (evt) {
alert("Load");
}
Hope that's how you wanted it to work.
You can check here for more info - DOMContentLoaded Event
Why does vanilla JS's onload work where jQuery's load on does not when it comes to loading scripts?
So...
thisScript.onload=function Event triggers as expected.
$(thisScript).bind({load:function Event does not trigger
$(thisScript).on({load:function Event does not trigger
JS load and jQuery onload both work fine when it comes to loading
thisImg.onload=function Event triggers as expected
is the same as...
$(thisImg).bind({load:function Event triggers as expected
$(thisImg).on({load:function Event triggers as expected
...but not for scripts.
I'm aware of $.getScript but I'm curious about the above discrepancy.
Question Is there an event binding for jQuery that works for script loading?
The following test is revealing:
window.onload=()=>
var thisSrc, thisScript, thisTest;
thisSrc="testScript.js"; //See contents below
thisTest="JS";
//thisTest="JQ";
if(thisTest=="JS"){
thisScript=document.head.appendChild(document.createElement("script"));
thisScript.onload=function(){
alert("Event Triggered"); //EVENT TRIGGERS AND THE SCRIPT LOADS.
}
thisScript.src=thisSrc;
}else if(thisTest=="JQ"){
thisScript=$("<script>")
.attr({src:thisSrc})
// .bind({
.on({
load:function(){
alert("Event Triggered"); //EVENT DOES NOT TRIGGER BUT THE SCRIPT LOADS.
}
})
.appendTo(document.head)[0];
}
}
Contents of testScript.js:
alert("Script Loaded");
Both JS and jQuery successfully load the script. It's just the JQ event listener that doesn't trigger.
Resolved -- issue is order of commands.
src needs to be defined after the <script> element is in the DOM and the listeners are assigned.
So this works reliably...
$("<script>")
.appendTo(document.head)
.on({
load:function(){
alert("Event Triggered");
}
})
.attr({src:thisSrc});
Order of .on and .appendTo can be reversed, but have happen before .attr
This code stopped working despite the fact that window.load works after ready.
$(document).ready(function () {
google.maps.event.addDomListener(window, 'load', function () { InitializeMap(); });
But If I write the code outside the ready function, it works fine.
$(document).ready(function () {
InitializeMap(); });
This code also works nice.
This is a jQuery related issue. jQuery uses its own internal deferred object to represent a list of "ready" callback functions. Within this deferred object there may or may not be timeouts set for various reasons, the window.onload is cancelled under some conditions, and more. jQuery does all of these things to ensure cross-browser consistency. From the jQuery documentation:
Note that although the DOM always becomes ready before the page is
fully loaded, it is usually not safe to attach a load event listener
in code executed during a .ready() handler. For example, scripts can
be loaded dynamically long after the page has loaded using methods
such as $.getScript(). Although handlers added by .ready() will always
be executed in a dynamically loaded script, the window's load event
has already occurred and those listeners will never run.
Reference
The plain JavaScript solution below works as you would expect since there isn't all that additional cruft that goes into jQuery's implementation of the same code:
document.addEventListener('DOMContentLoaded', () => {
google.maps.event.addDomListener(window, 'load', function() {
alert('custom event');
});
});
<script src="https://maps.googleapis.com/maps/api/js?v=3"></script>
Why does click event not firing in this case, although DOM appears to be loaded ('ready' shows in the console)?
$(document).ready(function() {
console.log("ready!");
});
$("p").click(function() {
alert("You clicked on paragraph.");
});
My understanding, that because code for click event is after document ready function is correctly executed, it should work, but it doesn't. It will only work when event is included between curly braces in ready function.
$(document).ready is asynchronous. You are passing a callback function to it so that it logs the fact the DOM is ready. However, the click binding code is being executed immediately after you set up the ready handler, not when the callback has executed.
You just need to make sure you put the binding logic within the ready handler.
If you want that code to be executed in the "ready" event, just move it there.
$(document).ready(function() {
console.log("ready!");
$("p").click(function() {
alert("You clicked on paragraph.");
});
});
The way you defined it right now doesn't mean it is executed when the DOM is loaded.
You can place the code directly in the $(document).ready() function or create a new function that binds the click when the DOM is ready.
$(document).ready(function() {
bindClickEvent();
});
function bindClickEvent() {
$("p").click(function() {
alert("You clicked on paragraph.");
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<p>Click me!</p>
I am just learning javascript. How do I bind this function on submit in document ready?
jQuery(function($) {
$('form').bind('submit', function() {
$(this).find(':select').removeAttr('disabled');
});
});
Thanks
$(document).ready(function() {
/* your code here */
$('form').bind('submit', function() {
$(this).find(':select').removeAttr('disabled');
});
/* end your code */
});
It is as simple as that - once the document is "ready", the binding will be put in place - for more clarification, head over to the jQuery tutorial website for information regarding the $(document).ready() event: http://learn.jquery.com/using-jquery-core/document-ready/
You have two options with jQuery for a document "ready" event :
$(document).ready(): When your dom is fully loaded, jQuery will trigger the ready event.
$(document).load() : jQuery waits until your dom and all your declared assets are loaded. So if you rely on css properties for your javascript code, use this one.
For additional information, please take a look at : http://api.jquery.com/ready/