Document write gives strange output

前端 未结 2 723
一向
一向 2021-01-25 01:41

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

相关标签:
2条回答
  • 2021-01-25 02:17

    try this one

    document.write("<script>window.jQuery || document.write('<script src=\"js/jquery.v1.9.1.js\"/>')<\/script>");
    
    0 讨论(0)
  • 2021-01-25 02:23

    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>");
    
    0 讨论(0)
提交回复
热议问题