12.5. Running a Script on Page Load

One solution to the previous problem is to run the script inside the window.onload() function, but the script will not be run until the entire page including images is loaded.

jQuery offers a neat solution with the ready event:

$(document).ready(function() {
    $("<p>hello I am dynamic text</p>").appendTo("body");
});

This is a good way to ensure that the page is loaded before the script and will resolve the earlier issue. You must ensure that you have added any elements to the page before running code that manipulates them.

Get Introducing .NET 4.0: with Visual Studio 2010 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.