Dynamically load a file and show it on a web page

Estimated reading time of this article: 2 minutes

Do you have written a script which you are using on a website and do you want to show the source file in pretty print?

This is was exactly the use case of HTML to Markdown converter using regex.

Surely, you can copy & paste the script to the web page. That works. However, it's a code duplication and on each improvement you have to copy the script again.

There's a smart way with jQuery. The script is loaded with AJAX, inserted in the web page (DOM), and pretty printed. Additionally, I'll initially hide the code with the possibility to toggle it.

The very same file is executed and shown on the web page.

Attention: Be aware of SmartyPants which could exchange quotes with typography quotes. In theory it should not interfere, however I had some problems.

Example

Show JavaScript source code

The JavaScript source file.

Code

Dependencies:

<a id="show_source_code" onclick="false">Show JavaScript source code</a>

<div id="jsSource" class="codeblock" style="display: none;"></div>

<div>

<!-- <script src="/sites/all/libraries/jquery-syntaxhighlighter/scripts/jquery.syntaxhighlighter.min.js"></script> -->
<script>
      (function ($) {
          $(document).ready(function() {
              /*$.SyntaxHighlighter.init({
                  'wrapLines':true,
                  'defaultCssClass': 'code-highlight',
                  'prettifyBaseUrl':'/sites/all/libraries/jquery-syntaxhighlighter/prettify',
                  'baseUrl': '/sites/all/libraries/jquery-syntaxhighlighter'
              });*/
             
          $("#show_source_code").click(function () {
             if ($('#jsSource').is(":visible")) {
                 $(this).html($(this).html().replace(/Hide/, 'Show'));
             } else {
                 $(this).html($(this).html().replace(/Show/, 'Hide'));
             }
             // Do it afterwards as the operation is async
             $("#jsSource").slideToggle("slow");
          });
   
          // Ref: http://stackoverflow.com/questions/6470567/jquery-load-txt-file-and-insert-into-div
          $.ajax({
              url : "/sites/scito.ch/files/static/regexhtml2md/regexhtml2md.js?v=1.0",
              dataType: "text",
              success : function(data) {
                  //$("#jsSource").html(escapedCodeTag(data)).syntaxHighlight();
                  $("#jsSource").html(prettyPrintOne(convertEOL(escapedCodeTag(data))));
              }
          });
      });
  })(jQuery);
</script>
</div>

The JavaScript [source file](/sites/scito.ch/files/static/regexhtml2md/regexhtml2md.js?v=1.0).

Additionally, three JavaScript helper functions.

/** Ref: http://stackoverflow.com/questions/1219860/javascript-jquery-html-encoding */
function htmlEscape(str) {
    return String(str)
    .replace(/&/g, '&amp;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;');
}

/** Ref: http://stackoverflow.com/questions/1219860/javascript-jquery-html-encoding */
function convertEOL(str) {
    return String(str).replace(/\n/g, '<br>');
}

/**
* Escapes the string and wraps it into a code tag.
*
* I had to outsource this due to problems with SmartyPants changing quotes of the scripts.
*/
function escapedCodeTag(str) {
    return '<code class="language-javascript" style="background: none;">' + htmlEscape(str) + '&lt;/code>';
}

I've written another article about the toggle, see Toggle content with jQuery; show/hide a block

References

Some helpful links: