0

Odd issue in Firefox (no problem in Chrome, IE (11 at least), and Safari). The following code was breaking the page and emptying the network profiler, page source, etc...

<script>
  var mainScriptSrc = '/scripts/app/site.js';
  var jQuerySrc = '/scripts/vendor/jquery/jquery.js';
</script>
<script>
  function loadMain(){document.write('<script src="'+mainScriptSrc+'"><\/script>');}
  window.jQuery || document.write('<script src="'+jQuerySrc+'" onload="loadMain()"><\/script>')
</script>

Anything stand out as odd?

Thanks,
Dan

danwoods
  • 4,889
  • 11
  • 62
  • 90

1 Answers1

0

When I run that code through the devtools in Firefox, I get SecurityError: The operation is insecure..

You could try doing this instead:

function addScript(path, onload) {
  var script = document.createElement("script");
  script.src = path;
  if (onload) {
    script.onload = onload;
  }
  document.body.appendChild(script);
}
function loadMain(){
  addScript("/scripts/app/site.js");
}
window.jQuery || addScript("/scripts/vendor/jquery/jquery.js", loadMain);

Be advised though, that using that logic (which is what you were doing in your original code), loadMain() is only run if jQuery wasn't already loaded. I don't know if that's what you intended...

Christian Sonne
  • 312
  • 1
  • 10
  • Ah, good catch on the "only loading site.js if jQuery isn't in `window`" issue. That was not my intent. I'm still interested as to why it would be a security issue, and why Firefox would dump the page contents (I suppose they could be related).. – danwoods Sep 16 '14 at 22:07
  • I can't explain the dumping of contents you are describing (at least without seeing it happen), but document.write() only works during the parse state, not after the document has finished loading. Props to [Henry Sivonen](https://twitter.com/hsivonen/status/512205402927534080) for pointing this out. – Christian Sonne Sep 17 '14 at 11:53
  • Actually, [this](http://stackoverflow.com/a/23787551/1848865) explains why you're seeing the whole document dumped. – Christian Sonne Sep 17 '14 at 13:51