elementReady

elementReady
 点击下载

Calls a function during page load as soon as a specific element is available — even before the full DOM is loaded. Useful for applying unobtrusive JavaScript to particular page elements immediately, without waiting for the whole DOM to load in a large page.

  1. $.elementReady(String id, Function fn) 

id is the ID of the element to wait for

fn is the callback function to be called when the element appears in the DOM; in the callback, "this" refers to the newly loaded element.

While a page is loading, call a given callback function as soon as a specific element is loaded into the DOM, even before the full DOM has been loaded. Executes the function within the context of the element. This means that when the passed-in function is executed, the ‘this’ keyword points to the specific DOM element.

The function returns ‘this’, so you can chain multiple calls to elementReady(). (Not that there’s much benefit in doing that.)

One argument is passed to the callback: a reference to the jQuery function. You can name this argument $ and therefore use the $ alias even in noConflict mode.

If the element has not been found by the time the DOM is fully loaded, then the function will not be called.

Example:

Change the source of a specific image as soon as it is loaded into the DOM (before the whole DOM is loaded).

  1. $.elementReady('powerpic', function(){ 
  2.     this.src = 'powered-by-jquery.png'
  3. }); 

Example:

If you want to have the jQuery object instead of the regular DOM element, use the $(this) function.

  1. $.elementReady('header', function(){ 
  2.     $(this).addClass('fancy'); 
  3. }); 

Example:

Chain multiple calls to $.elementReady().

  1. $.elementReady('first',  function(){ $(this).fancify(); }) 
  2. .elementReady('second', function(){ $(this).fancify(); }); 

Example:

Use the ‘$’ alias within your callback, even in noConflict mode.

  1. jQuery.noConflict(); 
  2. jQuery.elementReady('header', function($){ 
  3.     $(this).addClass('fancy'); 
  4. }); 

Example:

Change the polling interval to 100ms. This only works if $.elementReady() has not yet been called.

  1. // You probably don't need to do this 
  2. $.elementReady.interval_ms = 100; 

 

转载请注明:代码家园 » elementReady

评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)