jQuery $(document).ready and svg-web window.onsvgload - javascript

jQuery of course requires everything to be inside
$(document).ready = function() {};
similarly, svg-web requires:
window.onsvgload = function() {};
Is there a correct, elegant way to combine these that doesn't introduce any problems?

You can just bind the functions to run on the appropriate event, like this:
$(function() { //shortcut for $(document).ready(function() {
//stuff that needs the DOM to be ready
});
$(window).bind('svgload', function() {
//SVG stuff
});
There's no harm is using both, in fact that's the appropriate usage, always use the event you need, this is no different from document.ready vs window.load when you need images ready, not just the DOM.
If it matters, svgload happens after onload in the browsers that support it as of the time of this answer, not sure if that'll be consistent when other browsers support it though.

Finally found this in the 'user manual':
$(document).ready(function() {
window.addEventListener('SVGLoad', function() {
// ready to work with SVG now
}, false);
});

Related

What happens if multiple scripts set window.onload?

There are a number of posts on StackOverflow and other websites regarding the problem of avoiding namespace collisions. In my scenario, I just want a method in my JavaScript to be executed after the DOM is accessible.
If I do the following will it avoid namespace collisions?
<script type="text/javascript">window.onload = function() { //Define my namespace var here, and execute all my code }</script>
What if a script that is injected later also sets an onload function ? Will mine get overwritten? I'm fully aware that I can test this out, but I would also like some feedback as I am new to JavaScript and there could be a number of other scenarios which will do the something that I am not aware of.
EDIT: I need to support only Safari 5.0+
Yes, the last one will overwrite the previous ones.
The solution: use the new event API: addEventListener.
This is a fine Javascript way to do it right
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(nameOfSomeFunctionToRunOnPageLoad);
addLoadEvent(function() {
/* more code to run on page load */
});
Explained Source
There's lots of information on this, but here's the short version:
if you want to play nicely with onload, you can do
var prev_onLoad = window.onload;
window.onload = function() {
if (typeof(prev_onLoad)=='function')
prev_onLoad();
// rest of your onLoad handler goes here
}
and hope that other's play nicely or make sure that's the last setting of onload in the code.
However, more modern browsers have event registration functions (addEventListener and attachEvent on IE) which take care of this chaining among other things. Quite a few cross-browser onload event functions have been written which take care of this logic for you.
It'll be overriden .
In Javascript, when you define handle event like
window.onload = function(){
console.log("in Load function 1");
};
window.onload = function(){
console.log(" In load function 2");
};
That will make an " assign " window.onload => function() . And window.onload will be assign to last function .
But in jQuery,
You can handle event in many times and the browser will make all
$("body").on("click",function(){
console.log("make a callback function 1");
});
$("body").on("click",function(){
console.log("make a callback function 2");
});
Because jQuery make a callback not "assign".
Hope it helps you.

How to fire an event immediately?

I'm binding an event like this, using prototype js:
$('country').observe('change',function(e) { ... });
How can I fire it once immediately?
in jQuery, I'd just tack on a .triggerHandler('change'). Is there something similar in prototype?
Use the load event. Something like this:
// calls addListeners when the document loads
Event.observe(window, 'load', addListeners, false);
function addListeners() {
// called onLoad
fireOnce();
// observer for the country dropdown
$('country').observe('change', function(event) {
fireOnChange();
});
}
function fireOnce() {
// do something
}
function fireOnChange() {
// do something
}
When the document loads, fireOnce() will execute. I use this technique all the time.
If using an extension is an option, I have had success in the past with event.simulate for this purpose.
It'll allow you to do something like:
$('country').simulate('change');
Try this:
var handler = function(e) {...};
$("country").observe("change",handler);
handler();
Alternatively (less readable, avoids temporary variable):
$("country").observe("change",(function(e) { ... return arguments.callee;})());
However, in both cases you will not be able to use this as you might expect. This solution is better suited to more general callbacks such as for setInterval
...if you know that it exists, and you know that you're not waiting for pageload or waiting for a script to load, why not just:
(function (el) {
if (!el) { return; }
doSomething(el);
}(document.getElementById("country")));

jQuery $( function() {} ) and $(document).ready the same?

To have a working datepicker on a field, I have to put this script inside my element
$( function() {
$( "#date_datepicker" ).datepicker( { dateFormat: "yy-mm-dd" } );
});
Removing the $( function() { makes the datepicker not work.
So does it mean that the $( function() { is the same as $(document).ready?
I'm trying to optimize my javascript codes so knowing this might help.
See the extract below from http://api.jquery.com/ready/
All three of the following syntaxes are equivalent:
$(document).ready(handler)
$().ready(handler) (this is not recommended)
$(handler)
The .ready() method is typically used with an anonymous function:
$(document).ready(function() {
// Handler for .ready() called.
});
Which is equivalent to calling:
$(function() {
// Handler for .ready() called.
});
As can be read here
Yes, it's a shorthand version of the same thing. The $ function calls the $(document).ready function when passed a function as an argument.
If you're trying to optimise in terms of speed - both will perform pretty much equivalently, however the longer $(document).ready(handler) will be minimally faster if executed lots of times.
If you're trying to optimise in terms of file size - use a minifier.
IMO the best you can do is to 'optimise' in terms of readability and simplicity. This makes the code far easier to understand and maintain. There are tools out there to take an unoptimised version and compress and optimise for you (check out Google's closure compiler).
Yes, $( function() { and $(document).ready are same.
$( function() { works as a shorthand syntax but $(document).ready makes the code more readable.
Here is a pretty safe way to run code on ready
jQuery(function($, undefined){
// code to run onready
});
Although I personally prefer doing it like this:
(function($){ // create scope and pass specific aliased variables
$(function($, undefined){ // attach callback to run onready
// code to run onready
});
})(jQuery);
This way you can make your own bundles of functionality without fear of breaking other peoples code or having your code broken by loose variable definitions. You can also call the variables that you pass along with whatever names that you want and have code that runs no on ready, for example.
(function($){ // create scope and pass specific aliased variables
$(document).on('click', 'a[href]', function(){
// code to run when a link is clicked
});
$(window).on('load',function(){
// code to run onload
});
$(function($, undefined){ // attach callback to run onready
// code to run onready
});
})(jQuery);
Note that these are the same
$(document).bind('ready', function(){});
$(document).on('ready', function(){});
$(document).ready(function(){});
$(function(){});
And that document does not have a load event
$(document).on('load', function(){}); // will not work
note that you can also find scripts like this:
jQuery(document).ready(function(){
here the $-sign is replace by jQuery to avoid conflicts with other library's
http://docs.jquery.com/Using_jQuery_with_Other_Libraries
Are you using jQuerymobile? if so instead of using document ready use
$('#pageId').live('pageinit',function(){});

Clearing a jquery document.ready() call

How do I clear out anonymous functions that are set to trigger via a jQuery document.ready() call?
For example:
<script type="text/javascript">
//some code sets a doc ready callback
$(document).ready(function ()
{
alert('ready');
});
//my attempt to prevent the callback from happening
window.onload = null;
$(document).unbind("ready");
</script>
The alert happens regardless of my attempts to circumvent it. Is there any way to do this?
You'd probably get the most appropriate answer if you described what problem you're really trying to solve.
jQuery doesn't have a publicly documented way to undo or block document.ready() handlers. If you control the code, you can use a global variable and a conditional like this:
var skipReady = false;
$(document).ready(function ()
{
if (!skipReady) {
alert('ready');
}
});
// skip the document.ready code, if it hasn't already fired
skipReady = true;
Or, if you want to hack into jQuery a bit (beyond the documented interfaces), you can do this:
$(document).ready(function() {
alert("ready");
});
// stop the ready handler
$.isReady = true;
You can see this last one work here: http://jsfiddle.net/jfriend00/ZjH2k/. This works because jQuery uses the property: $.isReady to keep track of whether it has already fired the ready handlers or not. Setting it to true makes it think it has already fired them so it won't every do it again.
This works:
$(document).bind("ready", function () { alert("hey!"); });
$(document).unbind("ready");
Seems like a bug to me - all other events in jQuery are able to be unbound. Omitting this one is inconsistent.
Not a direct answer as to the omission, but here's some related info from jQuery docs:
All three of the following syntaxes are equivalent:
$(document).ready(handler)
$().ready(handler) (this is not recommended)
$(handler)
There is also $(document).bind("ready", handler). This behaves similarly to the ready method but with one exception: If the ready event has already fired and you try to .bind("ready") the bound handler will not be executed. Ready handlers bound this way are executed after any bound by the other three methods above.
$(document).ready() is dependent on the onLoad event which is triggered by the browser meaning you can not prevent it from happening. If the alert() is determined by some condition then I would use an if/else statement to decide whether it is called.
Super old question, but came across the need to do this recently to prevent document.ready code I didn't control from running in certain instances. This can be achieved by proxying jQuery's ready function, rather like a test spy. The following will work:
var ready = $.prototype.ready;
// proxy the ready function
$.prototype.ready = function ( fn, allowed ) {
allowed = allowed || false;
if ( allowed ) {
ready.call( this, fn );
}
};
All calls to $( document ).ready will now be ignored. You can override this behaviour by passing true as the second argument: $( document ).ready( fn, true )

How should I initialize jQuery?

I have seen this (I'm also using it):
$(document).ready(function(){
// do jQuery
})
and also this (I have tried lately):
(function(){
// do jQuery
})(jQuery)
both work fine.
What is the difference of the two (except on how it looks)?
Which one is more proper to use?
The second example you show is a self executing anonymous function. Every separate JS file you use would probably benefit from using it. It provides a private scope where everything you declare with the var keyword remains inside that scope only:
(function($){
var special = "nice!";
})(jQuery);
alert(special); // would be undefined
The first example is shorthand for $(document).ready which fires when the DOM can be manipulated.
A couple cool things about it. First, you can use it inside the self executing function:
(function($){
$(function(){
// Run on DOM ready
});
// Run right away
})(jQuery);
Secondly, if all you need is a few lines in document ready, you can combine both the private scope and the DOM ready function like this:
jQuery(function($){
// $ = jQuery regardless of what it means
// outside this DOM ready function
});
The first example runs the function when the DOM tree is built.
The second example runs the function right away.
If you look closely, in the second example, there are two parentheses after the function declaration ( in this particular case, you pass in the global jQuery object as an argument to avoid conflict ), thereby immediately invoking the function
The right function to use depends on when you want the function to run.
If you want to run a function on DOMReady ( the ready event ), you can use $( document ).ready like you mentioned or the shorthand $( function() {...} ).
Otherwise, if you want to run a function immediately and have anonymous function scope, use the second example.
In addition to all the previous answers,
jQuery have three initialization methods that can be used:
The traditional method compatible with most browsers, see code:
$(document).ready(function () {
});
The short-hand method, see code:
$(function () {
});
The implicit method, see code:
$().ready(function () {
});
They all work for modern browsers and safe to use.
I always use the first. The second appears to be a way to protect against jquery being overriden. One reason you might do this is if you don't know what other scripts will be loaded on the page. If all of your stuff depends on, say, jquery 1.3, and you're in an environment where you don't control the entire page, your code could break if someone loads in jquery 1.4. Sounds ugly, but this sort of thing does happen. So you can cover your butt by creating a closure immediately after you load jquery, and holding your version of jquery inside that closure. I think that's what's going on in the second example.
Neither one actually initializes jquery. Jquery takes care of any initilazation it needs on its own. You'd still, quite likely wind up using the first example even if you were using the second, you'd just be putting the $(document).ready inside the function in your second example.
Though it's an old conversation, I want to share my way to init jQuery
;(function($, window, document) {
// Your Code Goes Here
}(window.jQuery, window, document));
By this, you can sure about that nothing can go wrong.

Categories