7

I am getting a JavaScript error in my browser whenever I am trying to add the following two lines in the section of my application home page:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script>window.jQuery || document.write('<script src="<%=request.getContextPath()%>/resources/jq/jquery-1.10.2.min.js"></script>')</script>

Can someone please tell me what is wrong in those two lines? and if possible how to fix it?

Thanks for your time

2
  • 1
    the JS code works fine for me Commented Nov 5, 2013 at 13:48
  • Nested <script> tags will break the browser. Commented Nov 5, 2013 at 13:49

1 Answer 1

18

You can't embed the substring </script> anywhere within a script block.

Change your document.write call:

<script>
  window.jQuery || 
  document.write('<script src="<%=request.getContextPath()%>/resources/jq/jquery-1.10.2.min.js"></' + 'script>')
</script>

The browser "parses" <script> tag contents by blindly searching for a closing </script> tag, paying no attention whatsoever to the syntax of the contents.

Sign up to request clarification or add additional context in comments.

3 Comments

ah, good catch! I just tried the JS on the console and didn't see anything wrong :) +1
@Pointy so whenever I need to place a </script> tag within any script block all I have to do is split it into two concatenated strings to avoid getting them scanned by the browser...correct? Having said so this rule does not apply on the opening <script> tag?
@MChan yes that's right - the opening tag doesn't hurt anything because all the browser is looking for is the closing tag. Another way of doing it is to write it as '<\/script>' - the backslash-slash pair will end up as a plain slash in the string, but the browser won't think it's the closing tag.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.