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 do document.write I get a strange output

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

the output should come to:

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

but comes to:

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

can't figure out for the life of me whats wrong

Answers:

Answer

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>");
Answer

try this one

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.