// ==UserScript==
// @name document.load client injection
// @description inject the document.load implementation into real page context.
// @author jnd@chromium.org, based on idea from gurreiro_fabio@yahoo.com.br
// @match http://*/*
// @match file://*
// @match https://*/*
// @run-at document-start
// ==/UserScript==

// At first, we need to get head tag, then we will inject the script under
// head tag.
(function() {
  var injected_ = false;
  function InjectDocLoad(head) {
    if (injected_)
      return;
    injected_ = true;  
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.charset = "utf-8";
    script.src = "http://johnny.ding.googlepages.com/doc_load_impl.js";
    head.appendChild(script);
  }

  function GetHeadTag() {
   var head = null;
    try {
      head = document.getElementsByTagName('head')[0];
    } catch (e) {
      head = null;
    }
    return head;
  }

  function headInsertedChecker() {
    var head = GetHeadTag();
    if (head) {
      InjectDocLoad(head);
      document.documentElement.removeEventListener("DOMNodeInserted",
                                                   headInsertedChecker,
                                                   false);
    }
  }

  if (!document.documentElement) {
    // should not happen.
    return;
  }
  var head = GetHeadTag();
  if (!head) {
     document.documentElement.addEventListener("DOMNodeInserted",
                                               headInsertedChecker,
                                               false);
  } else {
    InjectDocLoad(head);
  }
})();