Category:Ajax site tips: Difference between revisions

From GreaseSpot Wiki
Jump to navigationJump to search
(Added example script.)
(Added "Listen for DOMNodeInserted event")
Line 15: Line 15:
* [http://userscripts.org/scripts/show/2419 Gmail attachment reminder]
* [http://userscripts.org/scripts/show/2419 Gmail attachment reminder]


== Listen for DOMNodeInserted event ==
This code is from Jesse Ruderman's [http://www.squarefree.com/userscripts/autolink.user.js?source Autolink] script:
var moddingDOM = false;
window.addEventListener("load", init, false);
function init()
{
  document.addEventListener("DOMNodeInserted", nodeInserted, false);
  setTimeout(go, 50, document.body);
}
// This makes it work at Gmail.
// 20% performance penalty on a plain text file with a link on almost every line.
// Tiny performance penalty on pages with few automatically added links.
function nodeInserted(e)
{
  // our own modifications should not trigger this.
  // (we don't want our regular expression objects getting confused)
  // (we want better control over when we recurse)
 
  //GM_log("Inserted: " + e.target);
 
  if (!moddingDOM)
    go(e.target);
}
=== Example scripts ===
* [http://www.squarefree.com/userscripts/autolink.user.js?source Autolink]





Revision as of 09:09, 13 April 2007

Ajax-driven or JavaScript-heavy sites often require different strategies than when scripting a regular site: elements appear, disappear and change at any time. This page contains some tips for scripting such sites.

Catch bubbling events

This code will tell you what element you click, unless it or some ancestor element does event.stopPropagation():

document.addEventListener('click',function(event) {
  GM_log("Clicked " + event.target);
}, true);

This is useful since elements you want to attach listeners to might not be in the DOM yet when the page/script loads.

Example scripts


Listen for DOMNodeInserted event

This code is from Jesse Ruderman's Autolink script:

var moddingDOM = false;

window.addEventListener("load", init, false);
function init()
{
  document.addEventListener("DOMNodeInserted", nodeInserted, false);
  setTimeout(go, 50, document.body);
}

// This makes it work at Gmail.
// 20% performance penalty on a plain text file with a link on almost every line.
// Tiny performance penalty on pages with few automatically added links.
function nodeInserted(e)
{
  // our own modifications should not trigger this.
  // (we don't want our regular expression objects getting confused)
  // (we want better control over when we recurse)
  
  //GM_log("Inserted: " + e.target);
  
  if (!moddingDOM)
    go(e.target);
}

Example scripts


This category currently contains no pages or media.