Skip to content Skip to sidebar Skip to footer

Document Write Gives Strange Output

I'm writing a script to detect jQuery, if it doesn't exist then insert the Google CDN version and a local fallback (don't ask why... it's not my idea), the problem is when I try to

Solution 1:

Basically, what's happening is that when document.write prints out

<script>window.jQuery || document.write('<script src=\"js/jquery.v1.9.1.js\"></script>')</script>

that first </script> is being parsed into the actual end-of-script tag, even though it's inside of a string, resulting in something like

<script>
    window.jQuery || document.write('<script src=\"js/jquery.v1.9.1.js\">
</script>
')
</script>

The string is not ended (unterminated string literal) because its closing single quote is now outside of the script, and there is also a dangling end-of-script tag. To stop this from happening, you simply need to escape like crazy the script tags inside the string, especially in the string inside the string. Below is a working example.

document.write("<script>window.jQuery || document.write('<script src=\"js/jquery.v1.9.1.js\"><\\\/script>')<\/script>");

Solution 2:

try this one

document.write("<script>window.jQuery || document.write('<script src=\"js/jquery.v1.9.1.js\"/>')<\/script>");

Post a Comment for "Document Write Gives Strange Output"