Before you ask, I already searched a lot in Stack Overflow and I google it thousand times. Any other case I ever seen here helped me.
Let’s go to my problem:
I’m trying to use the following script in my code:
<script type='text/javaScript'> document.write("<script src='/feeds/posts/default/-/"+hom_cat1+"?max-results=1&orderby=published&alt=json-in-script&callback=showhomeposts1'></script>"); </script>
But I’m using Blogger and it don’t detect correctly my code (note the red script closing tag):
With this, I can’t save the Template. So I’m trying to use convert my code into HTML entities using this website. When I encode, put this into my template and save, I get:
Uncaught SyntaxError: Unexpected token ILLEGAL
Here’s the encoded string I’m trying to use:
<script type='text/javaScript'>document.write("<script src='/feeds/posts/default/-/"+hom_cat1+"?max-results=1&orderby=published&alt=json-in-script&callback=showhomeposts1'></script>");</script>
What can I do to solve my issue?
Advertisement
Answer
The problem is that the string passed to document.write
includes the characters </script>
, which ends up prematurely terminating the script element that document.write
is called from.
The characters </script>
can’t appear anywhere within a script, since the HTML parser has no way to distinguish this from an actual </script>
tag.
You could try something like this instead:
document.write("<script src='...'></scr" + "ipt>");
Or, as mentioned in the comments:
document.write("<script src='...'></script>");
Another option is to use the DOM API to create a script
element and insert it into the document. The other answers here give some suggestions for that, but there are potential problems with the implementations (for example, document.body.appendChild
will throw a TypeError if you try to call it from within the head
). Something like this would be more robust:
(function() { var s = document.getElementsByTagName('script')[0]; var script = document.createElement('script'); script.src = 'http://something.com'; s.parentNode.insertBefore(script, s); }());
Also, type='text/javaScript'
is incorrect; use text/javascript
or omit the type
attribute.