Example: Replace an entire page with custom content
var newBody =
'<html>' +
'<head>' +
'<title>My New Page</title>' +
'</head>' +
'<body>' +
'<p>This page is a complete replacement of the original.</p>' +
'</body>' +
'</html>';
window.addEventListener(
'load',
function() { document.body.innerHTML = newBody; },
true);Looking closely at this code, you might naturally wonder why it works at all. I am declaring an anonymous function to pass
as the second argument to window.addEventListener, which accesses the newBody variable defined in the outer function. This is called a “closure”, and is perfectly legal in Javascript. In general, an “inner” function defined within an “outer” function can access all of the outer function's local variables -- even after the outer function finishes executing. This
is a very powerful feature that makes it possible to create event handlers and other functions that contain data structures
constructed at runtime.