SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Member
    Join Date
    Nov 2007
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    variable inside <script type='text/javascript'> tag

    This is what I am trying to do:

    Code:
    <script type="text/javascript">
    	document.write("<script type='text/javascript' src='" + id + ".js'></script>");
    </script>
    And i get the error: unterminated string constant.

    I have a .js file with some document.write statements, and i'd like to show the contents of this file but calling it with a variable.

    I've used something similar earlier in the page with no issues:

    Code:
    document.write('<link rel="stylesheet" href="style/' + brand + '.css" media="screen" />');
    So not sure why this is not working?

  2. #2
    SitePoint Author silver trophybronze trophy

    Join Date
    Nov 2004
    Location
    Ankh-Morpork
    Posts
    12,158
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi, and welcome to SitePoint Forums!

    The problem is the character sequence '</' that occurs inside your script element. That's not allowed.

    Due to the way the script element type is defined in HTML, any occurrence of '</' will be equivalent to </script>, thereby terminating your script element. In this case, it happens in mid-string, which is why you get the error message.

    The best solution is to use external JavaScript files only, but the workaround if you really need on-page scripting is to escape the offending character sequence by inserting a backslash character:
    Code JavaScript:
    <script type="text/javascript">
    	document.write("<script type='text/javascript' src='" + id + ".js'><\/script>");
    </script>
    Birnam wood is come to Dunsinane

  3. #3
    SitePoint Member
    Join Date
    Nov 2007
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Excellent - works perfectly and good explanation.

    Thank you.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •