Script loading: jQuery vs vanilla JS -- why a difference? - javascript

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

Related

events load and ready not firing

This is my code:
$(document).on('ready load click',function(){
console.log('hiihuhu')
})
I included the jquery script above.
The problem is the click event is firing but the load or ready event is not.
I don't see any error in my console.
What could be the problem?
Which Version of jQuery are you using
According to jQuery docs
$(document).on( "ready", handler ), deprecated as of jQuery 1.8 and removed in jQuery 3.0. Note that if the DOM becomes ready before this event is attached, the handler will not be executed.
$( window ).load(function() {
alert("hello");
});
$(document).ready(function(){
$(document).on('click',function(){
alert("in click event");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>hello</div>
Window onload: :Is fired when all the content including images has been loaded
document.ready : Is fired after html document is loaded
So i guess you cannot combine all three events ready,load and click the way you have tried
Hope it helps

When does $(document).load() execute? [duplicate]

What are differences between
$(document).ready(function(){
//my code here
});
and
$(window).load(function(){
//my code here
});
And I want to make sure that:
$(document).ready(function(){
})
and
$(function(){
});
and
jQuery(document).ready(function(){
});
are the same.
Can you tell me what differences and similarities between them?
$(document).ready(function() {
// executes when HTML-Document is loaded and DOM is ready
console.log("document is ready");
});
$(window).load(function() {
// executes when complete page is fully loaded, including all frames, objects and images
console.log("window is loaded");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Query 3.0 version
Breaking change: .load(), .unload(), and .error() removed
These methods are shortcuts for event operations, but had several API
limitations. The event .load() method conflicted with the ajax .load()
method. The .error() method could not be used with window.onerror
because of the way the DOM method is defined. If you need to attach
events by these names, use the .on() method, e.g. change
$("img").load(fn) to $(img).on("load", fn).1
$(window).load(function() {});
Should be changed to
$(window).on('load', function (e) {})
These are all equivalent:
$(function(){
});
jQuery(document).ready(function(){
});
$(document).ready(function(){
});
$(document).on('ready', function(){
})
document.ready is a jQuery event, it runs when the DOM is ready, e.g. all elements are there to be found/used, but not necessarily all the content.
window.onload fires later (or at the same time in the worst/failing cases) when images and such are loaded. So, if you're using image dimensions for example, you often want to use this instead.
Also read a related question:
Difference between $(window).load() and $(document).ready() functions
These three functions are the same:
$(document).ready(function(){
})
and
$(function(){
});
and
jQuery(document).ready(function(){
});
here $ is used for define jQuery like $ = jQuery.
Now difference is that
$(document).ready is jQuery event that is fired when DOM is loaded, so it’s fired when the document structure is ready.
$(window).load event is fired after whole content is loaded like page contain images,css etc.
From the jQuery API Document
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 stylesheets or embed style elements before
referencing the scripts.
In cases where code relies on loaded assets (for example, if the
dimensions of an image are required), the code should be placed in a
handler for the load event instead.
Answer to the second question -
No, they are identical as long as you are not using jQuery in no conflict mode.
The Difference between $(document).ready() and $(window).load() functions is that the code included inside $(window).load() will run once the entire page(images, iframes, stylesheets,etc) are loaded whereas the document ready event fires before all images,iframes etc. are loaded, but after the whole DOM itself is ready.
$(document).ready(function(){
})
and
$(function(){
});
and
jQuery(document).ready(function(){
});
There are not difference between the above 3 codes.
They are equivalent,but you may face conflict if any other JavaScript Frameworks uses the same dollar symbol $ as a shortcut name.
jQuery.noConflict();
jQuery.ready(function($){
//Code using $ as alias to jQuery
});
$(document).ready(function(e) {
// executes when HTML-Document is loaded and DOM is ready
console.log("page is loading now");
});
$(document).load(function(e) {
//when html page complete loaded
console.log("completely loaded");
});
The ready event is always execute at the only html page is loaded to the browser and the functions are executed....
But the load event is executed at the time of all the page contents are loaded to the browser for the page.....
we can use $ or jQuery when we use the noconflict() method in jquery scripts...
$(window).load is an event that fires when the DOM and all the content (everything) on the page is fully loaded like CSS, images and frames. One best example is if we want to get the actual image size or to get the details of anything we use it.
$(document).ready() indicates that code in it need to be executed once the DOM got loaded and ready to be manipulated by script. It won't wait for the images to load for executing the jQuery script.
<script type = "text/javascript">
//$(window).load was deprecated in 1.8, and removed in jquery 3.0
// $(window).load(function() {
// alert("$(window).load fired");
// });
$(document).ready(function() {
alert("$(document).ready fired");
});
</script>
$(window).load fired after the $(document).ready().
$(document).ready(function(){
})
//and
$(function(){
});
//and
jQuery(document).ready(function(){
});
Above 3 are same, $ is the alias name of jQuery, you may face conflict if any other JavaScript Frameworks uses the same dollar symbol $. If u face conflict jQuery team provide a solution no-conflict read more.
$(window).load was deprecated in 1.8, and removed in jquery 3.0

Target HTML generated by Javascript?

I have a slider button created using a JavaScript plugin, which automatically generates an element with class name .flex-next. However, when I run the following code, nothing is logged in my console:
$(window).load(function() {
$( ".flex-next" ).on( "click", function() {
console.log("youclick");
})
});
Since the button is added dynamically after the dom is loaded, you need to use event delegation so the click event can be used on this button:
$(document).on('click','.flex-nex',function() {
console.log("youclick");
})
Your setting your call to fire when the window loads by using $(window).load(...);. A flexsider is initiated on $(document).ready(...) which happens after the window loads and all of the content is loaded into the DOM. So when your script fires, it looks for an element that isnt there yet.
Get around this by firing your script on $(document).ready(), and use event delegation. The best practice way is to declare your function like so:
$(document).ready(
$(document).on('click', ".flex-next", function() {
console.log("youclick");
});
});
this way your click listener will wait until the page is ready and will put a click event on to any .flex-next event, even those created dynamically. That way if your using large imagery that is loaded asynchronously the code will still work.
You are probably calling your $(".flex-next").on call before the slider button has been executed. So, basically, your .flex-next class doesn't exist in the DOM yet when you call the .on
You should call the .on call after plugin has been initialized.

How to detect mobileinit and custom events through Javascripts AddEventListener?

I have an overrides.js script, which sets defaults in my application like so:
$(document).bind("mobileinit", function(){
$.mobile.autoInitializePage = false;
$.mobile.pushStateEnabled = false;
$.mobile.defaultPageTransition = "fade";
$('html').addClass('viewGrid');
console.log("mobileinit detected in overrides");
$(window).trigger('jqm-ready');
});
The overrides.js is pulled in via requireJS after Jquery has loaded and before Jquery Mobile loads. On my page I have this snippet in the footer:
console.log("page done loading");
window.addEventListener('jqm-ready', function(){
console.log("detected jqm-ready")
// run some code
});
document.addEventListener('mobilelinit', function(){
console.log("mobilelinit detected from page");
// run some code
});
My console displays the following:
page done loading
mobileinit detected in overrides
So, I'm not able to detect mobileinit or my custom jqm-ready event through my eventListener added on the page.
As I'm using requireJS I cannot use Jquery to detect mobileinit/jqm-ready, because the page is parsed before Jquery has loaded. I hoped to be able to detect either event, but no luck so far. I need to detect them because the code I need to run needs to bind to Jquery Mobile events.
Question:
Is there something wrong in my snippet or why can't I bind to either mobileinit or jqm-ready like this?
You have a typo in the event name, see:
document.addEventListener('mobilelinit', function(){
^----- TYPO HERE (should be mobileinit)
That is probably why you were not seeing the event.
Ok. I got it... I think I can't use Jquery's trigger for events that I added listeners to using addEventListener. But maybe not. Anyway this works:
var trigAnalytics = function( trigger ){
console.log("triggered by "+trigger);
};
document.addEventListener("jqm_ready",function(){console.log("jqm_ready"); trigAnalytics("jqm_ready");},false);
And in overrides.js
console.log("Hello now");
var evt = document.createEvent("Event");
evt.initEvent("jqm_ready",true,true);
document.dispatchEvent(evt);
Works.

jQuery change() fires on Page Load

This code fires on the page load, but not when the change event actually occurs.
jQuery('select#order_note_type').change(function() {
//random code here
});
I have to add that it is not inside the ready method. Do I need to bind it?
EDIT: I changed my code to be inside the $(document).ready() and used bind, but I still get my method to fire only at page load:
jQuery(document).ready(onReady);
function onReady() {
jQuery('select#order_note_type').bind('change',showTrackingInfo);
}
$(document).ready(function() {
$('select#order_note_type').bind('change',showTrackingInfo);
});
I had the same problem. In my case it was because I was firing some events on the controls after the code for the change event. So I suggest you try and move this change event to the end of your script, and also include this script last in the page.

Categories

Resources