\n

Why do developers share <script in JavaScript?

I see so many things like this: S = "<scr" + "ipt language=\"JavaScript1.2\">\n<!--\n";

Why do they do this, is there an application / browser that will go bad if you just use the direct "<script>" ?

+4
source share
2 answers

Take a look at this question:

external external external script external appearance < ,

Taken from bobince answer :

To see the problem, look at this vertex line in the script element:

 <script type="text/javascript"> document.write('<script src="set1.aspx?v=1234" type="text/javascript"></script>'); </script> 

So, the HTML parser comes in and sees the opening tag <script>. inside <script>, the usual <tag> parsing is disabled (in SGML terms, the element has CDATA content). Find where the script block ends, the HTML parser looks for a close-tag </script> match.

The first one he finds is the one inside the string literal. The HTML parser cannot know that it is inside a string literal, because HTML parsers do not know anything about JavaScript syntax, they only know about CDATA. So you actually say:

 <script type="text/javascript"> document.write('<script src="set1.aspx?v=1234" type="text/javascript"> </script> 

That is, an open string literal and an incomplete function call. These lead to JavaScript errors and the desired script tag is never written.

A common attempt to solve the problem is:

 document.write('...</scr' + 'ipt>'); 

This does not explain why this was done in the start tag.

+7
source

A more appropriate way to add scripts is to use the DOM.

  • Create an element of type <script> . See the documentation for document.createElement .
  • Set its attributes ( src , type , etc.)
  • Use body.appendChild to add this to the DOM.

This is a much cleaner approach.

0
source

All Articles