Display JavaScript Source Programatically

23rd March 2009 - 1 minute read time

If you are running a JavaScript example page you can use the following function that will take the last script element on the page and print it out in a code tag. It uses JQuery to do the work, so you will need to include that library before using this function.

  1. <script type="text/javascript">
  2. <!--//--><![CDATA[// ><!--
  3. //<![CDATA[
  4. function displaySource(name) {
  5. $('<code>'
  6. + $('#display-' + name).prevAll('script').eq(0).html()
  7. .replace(/^\s*|\s*$/g, '')
  8. .split('\n').slice(1, -1).join('\n')
  9. .replace(/(^|\n) /g, '$1')
  10. .replace(/('[^']*')/g, '<em>$1')
  11. + '
  12. //--><!]]>
  13. </script>
') .insertAfter('#display-' + name); } //]]>

The function works by selecting the current script tag and finding all script elements before it. It then selects the first one it finds and outputs the contents to a code tag. It uses a few regular expressions to convert some of the characters to a more human readable format. The function is called like this.

  1. <script type="text/javascript" id="display-test">
  2. <!--//--><![CDATA[// ><!--
  3. displaySource("test");
  4. //--><!]]>
  5. </script>

Add new comment

The content of this field is kept private and will not be shown publicly.