Blog

Web Dev Tip: Closing Script Tag Inside Javascript


Putting a closing script tag inside javascript strings will cause your javascript to break. The following code is suppose to just load the javascript library Jquery from the server and make the body background red. '); setTimeout( function() { $('body').css('background','red'); }, 2000 );   But it will not work, because of the  tag on the end of the string on line 2 The symptoms of this mistake is spilling  javascript code on your browser that usually starts with ') or ") Broken Javascript Output

Recommended Solution: String Break and Concatenate

To solve this you just have the get rid of tag by cutting the string in two With this it will work, but there are still other ways to do it, but I recommend the above solution.

Other Solutions

"Escaping" the forward slash (/)

Escaping the forward slash with backslash will also work ( <\/script> ) it appears to be cleaner, but for some reason Mozilla Developer Network article Values, variables, and literals says we should avoid this practice. This seems to work on other browsers and IE too.

DOM Manipulation

This method does not solve the closing script tag problem cause this actually removes it's existence. This is the same method google analytics use to prevent this error.

javascript:unescape() function

This (ugly fix) is used on old Google Analytics  

Conclusion

Therefore I then recommend the "String Break and Concatenate" solution versus other solution, but remember to use the proper quotation mark (single or double) when breaking and concatenating string

Comments (0)


Add a Comment





Allowed tags: <b><i><br>Add a new comment:


A Few Accomplishments

Integer eu ante ornare amet commetus vestibulum blandit integer in curae ac faucibus integer non. Adipiscing cubilia elementum integer. Integer eu ante ornare amet commetus.

Possibly broke spacetime

Integer eu ante ornare amet commetus vestibulum blandit integer in curae ac faucibus integer adipiscing ornare amet.

Terraformed a small moon

Integer eu ante ornare amet commetus vestibulum blandit integer in curae ac faucibus integer adipiscing ornare amet.

Snapped dark matter in the wild

Integer eu ante ornare amet commetus vestibulum blandit integer in curae ac faucibus integer adipiscing ornare amet.

Contact Me

Integer eu ante ornare amet commetus vestibulum blandit integer in curae ac faucibus integer non. Adipiscing cubilia elementum integer. Integer eu ante ornare amet commetus.