Home >Web Front-end >JS Tutorial >Closures and executing JavaScript on page load
This post expands on a previously published technique for executing JavaScript code after a webpage finishes loading. The core code utilizes JavaScript closures:
function addLoadEvent(func) { var oldonload = window.onload; if (typeof window.onload != 'function') { window.onload = func; } else { window.onload = function() { oldonload(); func(); } } } addLoadEvent(nameOfSomeFunctionToRunOnPageLoad); addLoadEvent(function() { /* more code to run on page load */ });
A closure bundles a function with its surrounding lexical environment (accessible variables). This is particularly powerful in JavaScript. Consider this example:
function createAdder(x) { return function(y) { return y + x; } } addThree = createAdder(3); addFour = createAdder(4); document.write('10 + 3 is ' + addThree(10) + '<br>'); document.write('10 + 4 is ' + addFour(10));
createAdder(x)
returns a function. Crucially, the returned function (a closure) "remembers" the value of x
from its creation context. addThree
adds 3, addFour
adds 4, demonstrating closure's state preservation.
The addLoadEvent
function leverages closures to manage multiple window.onload
handlers. If window.onload
is already defined, the new function is wrapped, ensuring both the existing and new functions execute sequentially upon page load. This allows chaining multiple calls to addLoadEvent
, creating a queue of functions executed on page load.
Closures are a potent tool but require understanding. Further exploration is recommended (see the Wikipedia article linked in the original post).
Frequently Asked Questions:
This section addresses common questions about JavaScript closures and page load execution, providing concise answers. The original FAQ section is retained, but reformatted for improved readability and conciseness. No information is lost. The questions and answers are paraphrased for better flow and to avoid redundancy.
The above is the detailed content of Closures and executing JavaScript on page load. For more information, please follow other related articles on the PHP Chinese website!