Show alert on page load using LAB JS - javascript

I inherited some code and all I want to do is run some jQuery code specifically an alert.
I know how to do that using jQuery/JavaScript but now sure if I can just use what I already have which is as follows:
<script>
$LAB
.script("js/lib/jquery-1.7.1.min.js").wait()
.script("js/lib/jquery.mobile-1.1.0.min.js").wait()
.script("../js/mobile/config/buildfile.js").wait()
.script("js/init.js")
.wait(function () {
$(function() {
setupHelpers();
loadApp(true,
function () {
},
function () {
});
});
});
</script>
Do I need to still use document.ready or can I just put that alert somewhere in the code above?
Thanks

The answer to if you need to wait for DOMready or not is separate from whether or not LABjs is in the picture. It's a common misunderstanding to conflate "DOMready" with "scripts are finished and ready", when in fact they're two separate events, and should be treated individually in terms of what you need.
So, to answer your specific question, should you wait for DOMready or not... the answer is, it depends on if you need the DOM or not to display the alert. If you're alerting to the user using the normal alert() dialog popup, then no you don't. If you're using some plugin which "alerts" the user by way of injecting a <div> into the DOM to show the alert, then yes you definitely need to wait for the DOM.
Whatever you do, don't fall for the fallacy that the "script loaded" event (which is what you get in your final wait(..) call) means the DOM is ready. This is not necessarily true.
Rule 1: if you need the DOM for some task, always wait using a DOMready event handler, don't assume.
Rule 2: if you need to wait for some or all scripts to finish loading, use a script-loaded event, like what a script loader like LABjs gives you.
Rule 3: if you need both the DOM and the scripts to finish loading, then compose both events, by embedding a DOMready handler in your script-loaded handler, as you have done above.

Related

is there a way to run the jquery.live function without any event

The live function of jQuery is triggered with an event
The api documentation is here
http://api.jquery.com/live/
$(".xyz").live('event', function(){
});
I want the above function to run without an event , i.e as soon as the class xyz is dynamically created.
I have tried this without the event parameter
$(".xyz").live( function(){
});
but it doesn't work !!
adding
I don't know exactly what you want to do, but I'll make assumptions.
Scenario 1
In order to execute a function inside jQuery, you need to tell jQuery when to execute the function, otherwise it cannot know. One way to do this is:
$(document).ready(function () {
$('.xyz').css('color', 'red');
// more code, anything, functions, calculations, etc.
});
The code inside that function will be executed as soon as your DOM is ready (is safe to manipulate).
You can put $('.xyz').css('color', 'red'); also outside the ready() event and it will also be executed. The "event" this time is when the executions of the page reaches that line of code. For example, if you put this line before your HTML, you don't have guarantee it will work.
Scenario 2 - onClassChange event
If you are looking for an event called something like onClassChange, it does not exits on jQuery. An approach to that problem could be this:
Create a timer which runs infinitely
On each run, check if that object has your class ( $(obj).hasClass('xyz') )
If yes, do whatever you want to do inside the if ()
Also, since you said the class xyz is created dynamically, you can try to run your function immediately after you create your class in your code.
For more about onClassChange event, there are long discussions you can check on this site.

When to use $(function() {}) when registering click handlers with jQuery?

What is the difference between
$(function()
{
$(".some").click(function()
{
...
});
});
and
$(".some").click(function()
{
...
});
I know from here that $(function() is shorthand for $(document).ready(function(). But why are we waiting for the document to be ready? Will the function not be only called when some is clicked anyway?
Note: #2 does not work in my case.
The difference is that #1 waits for the DOM to fully load before running the JavaScript.
The second code runs the JavaScript when it receives it which means it looks for .class elements before they have finished loading. This is why it doesn't work.
You need the document to be ready, i.e. all elements of the document to be available, before you can add an event listener to an element.
The reason is: consider a button, and you want an event listener (listening for the click event, for example.
When your sript runs but the button is not yet present, the attempt to attach the listener will fail. As a result, the associated function cannot be called once the button is actually clicked.
Does that answer your question?
You use the $(function()) simply because you need the DOM to fully load.
For example you have a button and you want to add some action on click. You click the button, but nothing happened, because the button was handled prior to the DOM loading.
If you won't check that the DOM is fully loaded, some unexpected behavior might occur.
Please do not confuse between onload() to ready(), as on load executes once the page is loaded and ready() executes only when the DOCUMENT is fully ready.
$(function(){...}) triggers the function when the DOM is load, it's similar to window.onload but part of jquery lib.
you can also use $(NAMEOFFUNCTION);
It's there to be sure the event has a element to listen to.

Is jQuery supposed to be used only in the ready event handler?

I have read code the uses jQuery outside of the ready handler, what are the drawbacks, if any to using it this way? For whatever reason I feel uncomfortable with it coded this way.
Inline script from and ASP.NET MVC View:
<script type="text/javascript">
function foo() {
if ($("#checkAll").attr("checked")) {
$(".setColumns").attr("checked", true);
}
else {
$(".setColumns").attr("checked", false);
}
}
</script>
There aren't really any drawbacks. It's just that you need to wait for the DOM element to be loaded before it can be manipulated. For example, if you had code like this:
<script type="text/javascript">
console.log($('#el').html());
</script>
<div id="el">Text</div>
The function would not return a value because the div was not yet loaded.
It is not.
The only reason why some people run it inside the document.ready handler, is because at that time, they can be sure the DOM tree is completely loaded, and your queries will return the correct results.
However, if you put your script tags underneath all elements, you normally would not have any issues with this.
The reason of using jQuery within the DOM ready handler is that event binding will only work when the element is present — if your DOM is not ready, your element may not be present and therefore the event may not be bound.
It is the same problem that people face when trying to bind events to dynamically loaded content without the .on() selector, for example — if the element is not initially present, events will not be bound to it.
p/s: You are of course free to define functions outside the handler.

jQuery document.ready

I am a little confused with document.ready in jQuery.
When do you define javascript functions inside of
$(document).ready() and when do you not?
Is it safe enough just to put all javascript code inside of $(document).ready()?
What happens when you don't do this?
For example, I use the usual jQuery selectors which do something when you click on stuff. If you don't wrap these with document.ready what is the harm?
Is it only going to cause problems if someone clicks on the element in the split second before the page has loaded? Or can it cause other problems?
When do you define javascript functions inside of $(document).ready() and when do you not?
If the functions should be globally accessible (which might indicate bad design of your application), then you have to define them outside the ready handler.
Is it safe enough just to put all javascript code inside of $(document).ready()?
See above.
What happens when you don't do this?
Depends on what your JavaScript code is doing and where it is located. It the worst case you will get runtime errors because you are trying to access DOM elements before they exist. This would happend if your code is located in the head and you are not only defining functions but already trying to access DOM elements.
For example, I use the usual jQuery selectors which do something when you click on stuff. If you don't wrap these with document.ready what is the harm?
There is no "harm" per se. It would just not work if the the script is located in the head, because the DOM elements don't exist yet. That means, jQuery cannot find and bind the handler to them.
But if you place the script just before the closing body tag, then the DOM elements will exist.
To be on the safe side, whenever you want to access DOM elements, place these calls in the ready event handler or into functions which are called only after the DOM is loaded.
As the jQuery tutorial (you should read it) already states:
As almost everything we do when using jQuery reads or manipulates the document object model (DOM), we need to make sure that we start adding events etc. as soon as the DOM is ready.
To do this, we register a ready event for the document.
$(document).ready(function() {
// do stuff when DOM is ready
});
To give a more complete example:
<html>
<head>
<!-- Assuming jQuery is loaded -->
<script>
function foo() {
// OK - because it is inside a function which is called
// at some time after the DOM was loaded
alert($('#answer').html());
}
$(function() {
// OK - because this is executed once the DOM is loaded
$('button').click(foo);
});
// OK - no DOM access/manipulation
alert('Just a random alert ' + Math.random());
// NOT OK - the element with ID `foo` does not exist yet
$('#answer').html('42');
</script>
</head>
<body>
<div id="question">The answer to life, the universe and everything</div>
<div id="answer"></div>
<button>Show the answer</button>
<script>
// OK - the element with ID `foo` does exist
$('#answer').html('42');
</script>
</body>
</html>
The document.ready handler is triggered when the DOM has been loaded by the browser and ready to be manipulated.
Whether you should use it or not will depend on where you are putting your custom scripts. If you put them at the end of the document, just before the closing </body> tag you don't need to use document.ready because by the time your script executes the DOM will already be loaded and you will be able to manipulate it.
If on the other hand you put your script in the <head> section of the document you should use document.ready to ensure that the DOM is fully loaded before attempting to modify it or attach event handlers to various elements. If you don't do this and you attempt to attach for example a .click event handler to a button, this event will never be triggered because at the moment your script ran, the jQuery selector that you used to find the button didn't return any elements and you didn't successfully attach the handler.
You put code inside of $(document).ready when you need that code to wait for the DOM to load before executing. If the code doesn't require the DOM to load first to exist, then you can put it outside of the $(document).ready.
Incidentally, $(function() { }) is short-hand for $(document).ready();
$(function() {
//stuff here will wait for the DOM to load
$('#something').text('foo'); //should be okay
});
//stuff here will execute immediately.
/* this will likely break */
$('#something').text('weee!');
If you have your scripts at the end of the document, you dont need document.ready.
example: There is a button and on click of it, you need to show an alert.
You can put the bind the click event to button in document.ready.
You can write your jquery script at the end of the document or once the element is loaded in the markup.
Writing everything in document.ready event will make your page slug.
There is no harm not adding event handlers in ready() if you are calling your js functions in the href attribute. If you're adding them with jQuery then you must ensure the objects these handlers refer to are loaded, and this code must come after the document is deemed ready(). This doesn't mean they have to be in the ready() call however, you can call them in functions that are called inside ready() themselves.

second $(document).ready event jQuery

I'm using some external jQuery with $(document).ready() to insert adverts after the document ready event has fired, something like:
$(document).ready( function() {
$('#leaderboard').html("<strong>ad code</strong>");
});
This is to prevent the UI being blocked by the slow loading of the adverts. So far it's been working well.
Now I need to insert some more ads though our CMS system, this can't be part of the external JS file, so I'm wondering can I use a second document ready event and insert it using an inline script tag? If so, what will be the order of execution the external JS document ready event first or the inline script?
You can use as many event methods as you want, jquery joins them in a queue. Order of method call is same as definition order - last added is last called.
A useful thing may be also that, you can load html code with script using ajax and when code is loaded into DOM $().ready() also will be called, so you can load ads dynamically.
Yes, adding multiple $(documents).ready()s is not a problem. All will be executed on the ready event.
Note however that your code sample is wrong. $(document).ready() takes a function, not an expression. So you should feed it a function like this:
$(document).ready( function() {
$('#leaderboard').html("<strong>ad code</strong>");
});
That function will be executed when the document is ready.
Here's a little tutorial on Multiple Document Ready
An added bonus of the jQuery way is
that you can have multiple ready()
definitions. This is the case with all
jQuery events.
$(document).ready(function () {
alert("Number One"); });
$(document).ready(function () {
alert("Number Two");
JQuery calls the ready functions in the order they are defined.
If you want to load some data first and deleay execution use holdReady().

Categories

Resources