Dynamically load a file and show it on a web page

Estimated reading time of this article: 1 minute 56 seconds

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.


Show JavaScript source code

The JavaScript source file.



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

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


<!-- <script src="/sites/all/libraries/jquery-syntaxhighlighter/scripts/jquery.syntaxhighlighter.min.js"></script> -->
      (function ($) {
          $(document).ready(function() {
                  'defaultCssClass': 'code-highlight',
                  '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
          // Ref: http://stackoverflow.com/questions/6470567/jquery-load-txt-file-and-insert-into-div
              url : "/sites/scito.ch/files/static/regexhtml2md/regexhtml2md.js?v=1.0",
              dataType: "text",
              success : function(data) {

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


Some helpful links: