3

I've implemented part of this script to help me with debugging

var ZFDebugLoad = window.onload;
window.onload = function(){
   if (ZFDebugLoad) {
      ZFDebugLoad();
   }
   ZFDebugCollapsed();
};

Firebug gives me the error "break on Error too much recursion"

The code to me looks like an endless loop so I'm wondering why the original author put it in. Also there's no return in the function, so ZFDebugLoad would never have a value...

EDIT The actual cause for this error (for any other people that followed the same tutorial I did, the cause to the error was this line

$response->setBody(preg_replace('/(<head.*>)/i', '$1' . $this->_headerOutput(), $response->getBody()));

which uses the regex pattern /(<head.*>)/i, this caused the script to be appended into my HTML5 <header> tag, t correct this I inserted a space into the pattern /<head(?!er).*?>/i

Moak
  • 12,596
  • 27
  • 111
  • 166

2 Answers2

2

ZFDebugLoad saves the old value of window.onload, and then replaces it with another function.

On window load it runs the original function first, if it had one, and then runs ZFDebugCollapsed.
You don't need a return value. In JavaScript, functions are values. if (ZFDebugLoad) check whether ZFDebugLoad is undefined or not, that is, whether you already had a window.onload function before running the script. If it isn't udefined, it can be executed.

Kobi
  • 135,331
  • 41
  • 252
  • 292
  • So why does Firebug say to much recursion,isn't that a sign that it's trying to execute a bajillion times? – Moak Mar 09 '11 at 06:11
  • @Moak - I've checked, and it seems to be working correctly: http://jsbin.com/onaye4 , so the problem is most likely somewhere else. It is possible the original function has an infinite recursion, that `ZFDebugCollapsed` has one, or that the scenario is more complex than displayed (for example, the whole code is contained in a function that is bound to `onload`) – Kobi Mar 09 '11 at 06:14
  • I see, then I'll need to figure that out, it was probably triggered by other jQuery plugins, because when I disable all but that script it does works without causing the error. – Moak Mar 09 '11 at 06:23
2

If the above script is loaded twice, then it'll recurse indefinitely.

The first time you load the script, it'll behave as expected. However, the second time you load the script, the original value of the window.onload will be lost, and both the window.onload and the ZFDebugLoad values will be the same function.

Since the window.onload is now checking for ZFDebugLoad, which is defined, it'll run that, but that's now the same function, so it'll again check ZFDebug, which is defined, it'll run that, but ...

Ad infinitum.

Arafangion
  • 11,517
  • 1
  • 40
  • 72