How to include a script inside a script tag


What if you needed to document.write a script within a script element like below:

<script>
  document.write('<script src="file.js"></script>');
</script>

Unfortunately, it will fail to parse since the </script> inside the JavaScript literal would be interpreted as a closing tag.

Essentially, the HTML parser would interpret the markup as:

<script>
  document.write('<script src="file.js">
</script>
');</script>

So how can you prevent this behavior?

Solution 1

You can split the </script> string:

<script>
  document.write('<script src="file.js"></' + 'script>');
</script>

Solution 2

You can replace < with \x3C:

<script>
  document.write('\x3Cscript src="file.js">\x3C/script>');
</script>

Solution 3

You can append a script element:

<script>
  var script = document.createElement('script');
  script.src = 'file.js';
  document.write(script.outerHTML);
</script>