SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Member
    Join Date
    Jun 2006
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    thoughts about addLoadEvent

    Hi all,

    i am trying to use addLoadEvent presented at http://www.sitepoint.com/blogs/2004/...-on-page-load/

    the idea is to execute a javascript function at page load, which would check element IDs at document and generate a new unique one, to use at a block ( DIV) also appended on load;

    so, the idea is to be nice to other javascript which could be defined at page, and make possible to run all needed functions at window.onload;

    the problem i find is that after using addLoadEvent it could happen that other javascript isnt nice, and overwrites the window.onload (before page is loaded as well ..);

    would you know a way to avoid this, diferent from get sure addLoadEvent is the last touching windows.onload? (something quite dificult if placing javascript anywhere

    thank in advance for your commetns, ideas sugestions ...

  2. #2
    Caveat surfer Buddy Bradley's Avatar
    Join Date
    May 2003
    Location
    Cambridge, UK
    Posts
    2,366
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Check the other Javascript you are using and replace any window.onload calls?

  3. #3
    SitePoint Addict dek's Avatar
    Join Date
    Oct 2004
    Location
    UK
    Posts
    352
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Well - there's a few ways. The best thing is not to use window.onload, but to be a little more modern & use addEventListener / attachEvent.

    Simplest approach:
    Code:
    function addLoadEvent(fn)
    
    {
    	if (window.addEventListener)
    		window.addEventListener('load', fn, false)
    	else if (window.attachEvent)
    		window.attachEvent('onload', fn);
    }
    The only problem with this is that the order in which the load events will fire is different in different browsers. We can get around this, however, by combining techniques a little.


    Code:
    function addLoadEvent(fn)
    
    {
    	if (!window.loadEvents) {
    		window.loadEvents = [];
    		var loadFn = function() { for (var i=0,f;(f=window.loadEvents[i]);i++) f(); }
    		if (window.addEventListener) 
    			window.addEventListener('load', loadFn, false)
    		else if (window.attachEvent) 
    			window.attachEvent('onload', loadFn);
    	}
    	
    	window.loadEvents.push(fn);
    }
    Only dead fish go with the flow


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •