简体   繁体   中英

Display external javascript content as text in html page

I am trying to display javascript code that is linked to the html page using a script tag as text on the same html page (and also syntax highlighted) as a tool for users to see the underlying javascript code.

Eventually I also want to display the html and css file contents as a learning tool so users can see all the components in a user-friendly manner on the same page (at the bottom in a tab control).

The other requirement is that the files are local and not stored on a web server. And last but not least I would like to keep this as simple as possible (no jQuery, no additional javascript if possible).

I have tried a couple of approaches without much success:

  • using HTML5 import and AJAX, encountered CORS and local file access errors
  • embed HTML5 tag, encountered prompt to execute javascript, not good
  • iframe tag , encountered prompt to execute javascript, not good

I am looking for simple and working solutions, I have searched quite a bit, but it is difficult to find something where you want to "convert" javascript into plain text and display it on an HTML page.

Extracting the src attribute from the script element and loading the file content via a separate HTTP call is probably the most feasible solution.

An example for the lodash source code, using jQuery:

 var src = $('#lodash').attr('src'); $.get(src, undefined, function(data) { $('#content').text(data); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script id='lodash' src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.js'></script> <pre id='content'></pre> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM