0

I'm curious why the code bellow displays "Why this text appears on load" on the page?

<!DOCTYPE html>
<html lang="en">
<head>
<title>Hello title</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script>
$(function() {
    $('<h4>Why this text appears on load</h4>').click(function() {
        alert('3');
    }).insertAfter($('h1'));
});
</script>
</head>
<body>
    <h1>H</h1>
</body>
</html>
Haradzieniec
  • 9,086
  • 31
  • 117
  • 212

3 Answers3

4

In jquery.js, jQuery is listening for the DOM to be ready by either using the DOMContentLoaded event, or the document.onreadystatechange event. Once the dom is ready, all callbacks that have been passed to .ready() are triggered, and any calls to .ready() that come after that are immediately executed.

Note: $(function(){}) is equivalent to $(document).ready(function(){})

Kevin B
  • 94,570
  • 16
  • 163
  • 180
  • it should also be noted that, except in a small number of scenarios, $(window).on('load') is considered best practice, compared to $(document).ready(). – PlantTheIdea Feb 04 '13 at 16:20
  • 1
    I wouldn't consider that best practice at all. – Kevin B Feb 04 '13 at 16:21
  • 1
    If you want your page to appear to load fast (which is far more important than the page being completely loaded fast) you definitely should not be waiting for the window load event. – Kevin B Feb 04 '13 at 16:23
  • if u want to ensure that all elements have been loaded to be properly accessed, you definitely should not be expecting it to work on document ready. http://www.theextremewebdesigns.com/blog/jquery-document-ready-vs-window-load/ – PlantTheIdea Feb 04 '13 at 16:24
  • and proper coding combined with minifying your scripts = fast. if you see a discernable difference in speed between doc ready and win load, you coded poorly and need to clean it up. – PlantTheIdea Feb 04 '13 at 16:25
  • @LifeInTheGrey: I think you have it backwards. Except in a small number of scenarios, `$(document).ready()` is considered best practice compared to `$(window).on('load')`. `window.load` is only needed when querying image sizes (and a few other things). http://stackoverflow.com/a/8396457 – gen_Eric Feb 04 '13 at 16:26
  • 1
    How often do you need to get the size of elements in the dom with Javascript? In my opinion that'd be the only time you would want to use window load instead of document ready. – Kevin B Feb 04 '13 at 16:27
  • awesome, your stack overflow link does a great job of explaining the application of the different things. The checkmarked answer links to a wordpress site with this quote - "Therefore functions which concern images or other page contents should be placed in the load event for the window or the content tag itself." i know not many people use images on web pages nowadays, i guess im old school. – PlantTheIdea Feb 04 '13 at 16:28
  • @LifeInTheGrey: Thanks for the sarcasm, I needed that. I'll Google around and find a better answer to link you to, as that one didn't explain the difference that well. ``. Anyway, `document.ready` is *faster* than `window.load`. `window.load` is only needed if you need to wait for images, iframes, and objects to load. If you don't then you can speed the page up a bit by using `document.ready`. – gen_Eric Feb 04 '13 at 16:37
  • 1
    @RocketHazmat - appreciate the effort, but I understand the different applications. If you never need to concern urself with physical size of elements (images, but also others), document ready is just fine and is indeed faster. I've just had too many noobs ask why they're dynamically set height or something isn't working with doc ready. win load will run later and therefore can be slower, but it guarantees all elements are available, and is mitigated by proper coding and minification. like anything else, it depends on how u are using it, so perhaps my 'best practice' line was too hasty. – PlantTheIdea Feb 04 '13 at 16:40
  • @LifeInTheGrey: Ok, that I agree with. Sorry if I misunderstood you before. I didn't mean to be rude :-) – gen_Eric Feb 04 '13 at 16:41
  • 1
    oh no all good, im sure my sarcasm didn't help things haha. – PlantTheIdea Feb 04 '13 at 16:43
2

$('<h4>Why this text appears on load</h4>') is inserted after insertAfter($('h1')); on document.ready()

$(function() {}) is short form of document.ready(function() {}) which is executed as soon as the html element in the page are available.

Adil
  • 146,340
  • 25
  • 209
  • 204
  • Thank you for your explanation, but it is still not clear. On Document ready runs $('

    Why this text appears on load

    ').click(function() { alert('3'); }).insertAfter($('h1')); OK, but $('

    Why this text appears on load

    ') is an object. It it not on the page yet. If click event wasn't triggered yet, why .insertAfter($('h1')) was executed then?
    – Haradzieniec Feb 05 '13 at 07:45
2

$(function(){}) is shorthand for $(document).ready(function(){}). So, when the document (the DOM) is ready, your code runs.

You create an <h4> element, assign a click handler to it, then append it after each <h1> on the page.

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
  • You create an

    element - correct. Assign a click handler to it - correct, but not clicked yet. Append it after each

    on the page - why does it happen even if it was not clicked yet?

    – Haradzieniec Feb 05 '13 at 09:49
  • 1
    @Haradzieniec: Only code *inside* the function runs when the element is clicked. The `insertAfter` is ran because it's *outside* the click event. `.click()` returns the element, so you can chain jQuery methods, like you did. – gen_Eric Feb 05 '13 at 14:06