jhhayashi
jhhayashi

Reputation: 362

Browser interpreting Javascript string as HTML tag

I have the following in my source HTML:

<head>
    ...
    <script>window.jQuery || document.write('<script src="/js/jquery.min.js"></script>');</script>
    ...
</head>

But it is getting interpreted by my browser (Chrome) as:

<head>
    ...
    <script>window.jQuery || document.write('<script src="/js/jquery.min.js"></script>
</head>
<body>
    "');"
    ...

I've tried escaping the slash inside the document.write string, but that didn't work. Does anyone know how to prevent the browser from interpreting it as as a closing script tag?

Upvotes: 0

Views: 564

Answers (2)

Michael Giovanni Pumo
Michael Giovanni Pumo

Reputation: 14774

You need to escape some characters in your script.

Try this:

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

I escaped the / character with a backslash \, so it ends up like: \/ in your document.write() statement.

For a good example of this setup, try looking at HTML5 Boilerplate project on GitHub here:

https://github.com/h5bp/html5-boilerplate/blob/master/src/index.html#L26

Hope this helps.

Upvotes: 2

jcubic
jcubic

Reputation: 66488

</script> is alwasy interpreted as closing script tag even if it's inside string you need to split it like this:

'</'+'script>';

Upvotes: 5

Related Questions