0
  1. I have page with many doubleclick scripts
  2. I have js code inserted at the body top (via s.src=('parts_async_dev.js')):

    var innerHTML = document.getElementsByTagName('html')[0].innerHTML.toString();
    var regexp = /ad.doubleclick.net/gm;
    var matches = innerHTML.match(regexp);
    alert('found ' + matches.length + ' tags by regexp ' + regexp);
    console.log( innerHTML);
    

alert says that matches returns only 2 of ad.doubleclick.net tags. I thought first that code can not access whole body if not placed at the body very bottom. But it finds 2 tags inside div "interstitial_wrapper" which comes after my code.

So my questions are:

  • why is it so
  • How to access whole body form body start ( i may not use body 'onload' event. it is required to use script asap)

Please take a look at http://wap7.ru/folio/bannerstat/partners/doubleclick2.html and see view source, because it is too large to include here.

Lev Savranskiy
  • 422
  • 2
  • 7
  • 19

1 Answers1

2

You don't have to bind to the onload event. Just bind to the DOMContentLoaded event.

Since you've already included jQuery in your page, this can esily be done using .ready:

$(document).ready(function() {
    var innerHTML = document.body.innerHTML;
    /* If you want to use a RegExp, use the following:
    var regexp = /ad\.doubleclick\.net/gi; // Note: escaped dot
    var matches = innerHTML.match(regexp);
    matches = matches ? matches.length : 0; // matches can be `null`
    */

    // This is more effective:
    var matches = innerHTML.split('ad.doubleclick.net').length - 1;
    alert('Found ' + matches + ' tags.');
    console.log( innerHTML );
});
Rob W
  • 341,306
  • 83
  • 791
  • 678
  • Thanks! i cant rely on jquery since it is not my page. i do **window.addEventListener('DOMContentLoaded', func, false);** see http://en.wikipedia.org/wiki/DOM_events#Other_events for details – Lev Savranskiy Feb 21 '12 at 14:28
  • @Lev Before doing so, check whether the page has already fired the `DOMContentLoaded` event, via [`document.readyState`](https://developer.mozilla.org/en/DOM/document.readyState). – Rob W Feb 21 '12 at 14:31
  • since my code is in very top i am not sure if it is possible to have ready state loaded. – Lev Savranskiy Feb 21 '12 at 15:05
  • any way i use such snippet. is it correct? `function addDOMContentLoadedEvent(func) { // debug(document.readyState); if (document.readyState == 'interactive' || document.readyState == 'complete' ){ func(); }else{ if (window.addEventListener) { window.addEventListener('DOMContentLoaded', func, false); } } }` – Lev Savranskiy Feb 21 '12 at 15:06
  • @Lev Kind of (you're ignoring IE). Have a look at this Stack Overflow Q&A for a cross-browser implementation: [$(document).ready() source](http://stackoverflow.com/q/3430455/938089?document-ready-source). – Rob W Feb 21 '12 at 15:15