Alex
Alex

Reputation: 11

Javascript launching with (or without) document.writeln?

I have been looking at some tracking issues and have a question pertaining to the launching of scripts. Can someone tell me if there is a difference between:

<script type="text/javascript" src="http://www.example.com/universalPixel.html"></script>

and

<script language="JavaScript"> document.writeln('<scri' + 'pt type="text/javascript" src="http://www.example.com/universalPixel.html"></scri' + 'pt>');</script>

I have seen these two variations and unfortunately have not been able to discern if there is a significant difference dependent on the inclusion of the document.writeln method. Or perhaps another distinction that I am unaware of.

Thank you for your help.

Alex

Upvotes: 1

Views: 754

Answers (2)

mellamokb
mellamokb

Reputation: 56779

document.writeln is probably used to dynamically include a script, using that strange string concatenation method because the browser processes </script> appearing anywhere as the end of the script tag, even inside of a JavaScript string. So the following would not work correctly for that reason:

<script type="text/javascript">
    // code

    document.writeln('<script type="text/javascript" src="..."></script>");
    // ^^ the </script> above ends the previous <script> tag prematurely.

    // more code
</script>

But there are better methods:

  1. Just include them normally, using <script src="..">
  2. Dynamically generate includes using server-side code (i.e., PHP) instead of JavaScript
  3. Use a JS library that provides dynamic library loading.

Upvotes: 3

Tejs
Tejs

Reputation: 41256

Since document.writeLn is discouraged in XHTML, you should attempt to use option 1. Many strict browsers will even ignore the second item if the appropriate doctype is used.

Upvotes: 1

Related Questions