Community Pick: Many members of our community have endorsed this article.
Editor's Choice: This article has been selected by our editors as an exceptional contribution.

Reading Files Into Your Web Page With JavaScript

"That which we persist in doing becomes easier, not that the task itself has become easier, but that our ability to perform it has improved."

Ralph Waldo Emerson

1. Introduction

One of the wonderful things about the web is that it makes it so easy to look up information.  This is especially true when it comes to finding an answer to a web design problem.  For every problem, it seems, there are hundreds code examples on dozens of sites showing how other developers have solved the problem.  If you look closely you may find there are really only a few ways to solve a certain problems and most of the code snippets rehash the same old solutions.

When looking for code samples on how to read files with JavaScript you will find the same few methods used over and over. Some of those examples are outdated, contain hacks which are no longer needed or are just plain wrong. There are web developers even today who advise that you can not read files with JavaScript. They are wrong! There is a modern, cross browser and elegant solution available in the remote scripting object.

All modern browsers now support remote scripting.  The remote scripting object is also slated for inclusion in the W3C's DOM 3 specification for the next generation of web browsers. Thus it is a firmly established technology.  As long ago as IE 7, you could use the same syntax to create a remote scripting object as is used by Mozilla, Safari, Opera, Chrome, et. al., and which is also used in the DOM 3 specification.

While this article may seem trivial to some, it receives the highest number of hits on my web site and has been used by many other people as the answer to the "How do I read files with JavaScript" question here and on numerous other IT Q&A web sites. Given that popularity, I can only assume that we are welcoming a whole new group of web developers to our ranks, and they are looking for solid code examples.

Even if you are familiar with the remote scripting object, (also known as the XMLHTTP or just XHR object,) what is unique in this code is that it has been written as a library file and allows file reading via the remote scripting object is as simple as a server side include or the PHP include() function. This code improves error handling, removes some redundant code and adds a couple of options for the developer over previous versions and when compared to similar examples you might find on the web. It also allows multiple "includes" on a given web page, and supports displaying a image to indicate content is being loaded.

The example code was written so it degrades nicely in older browsers which do not support the remote scripting object, or for browsers which have disabled JavaScript.

To see a live example of using remote scripting to read files into a web page please visit the page at the following link. Read File [Live Example].  The live example of the client side include function demonstrates the ability to gracefully fallback for non-remote scripting enabled browsers. The source code for the example is shown on that page but will be included here so we can look a little closer at that code's functionality.

2. Use Of The File Reading Library

Our JavaScript calls a function which uses the remote scripting object to get the file at the URL passed to the function. The file is simply returned to the page as a string of characters which are loaded into an HTML division. The string returned could be placed in nearly any HTML container, such as in paragraph tags or a span. To call the function is simple, for example;

<input type="button" value="Include File" onclick="include('');">

Open in new window

In this example we use the body "onload" event to execute the "include(path/to/file.txt)" command. The include function can be called in many different ways, including from another function, any page event, a link or a button. As written in the example, the content of the remote page is not returned by the "include" function, but are received by a results handling function.
As previously mentioned, this code adds additional flexibility by allowing you to specify the results handling function, and optionally a image to indicate the remote contents are being loaded.  So  in the code, we would use:

include(URL[, optionalTargetElementId][, optionalLoadingImageSourcePath]);

Open in new window

3. The Include File Code

                      // Does this browser support try-catch?
                      var tc = false;
                      try {
                          tc = true;
                      } catch(f) { }
                      var xmlHttpError = 'XML HTTP Request: OK';
                      function getRequestObject() {
                          var objRequest;
                          if (window.ActiveXObject) {
                              if (tc) {
                                  try {
                                      objRequest = new ActiveXObject('Msxml2.XMLHTTP');
                                  catch(e) {
                                      try {
                                          objRequest = new ActiveXObject('Microsoft.XMLHTTP');
                                      catch(f) { } 
                              } else {
                                  objRequest = new ActiveXObject('Microsoft.XMLHTTP');
                          } else if (window.XMLHttpRequest) {
                              objRequest = new XMLHttpRequest();
                          return objRequest;
                      function include(pUrl,pElementId,pImageSrc) {
                          if (arguments.length==3) {
                              if (pImageSrc) {
                                  var el = document.createElement('img');
                                  // Add the Please Wait Image
                                  el.setAttribute('src', pImageSrc);
                                  el.setAttribute('alt', 'Please Wait');
                                  el.setAttribute('width', 16);
                                  el.setAttribute('height', 16);
                          var objRequest = getRequestObject();
                          if (typeof(objRequest)=='object') {
                              if (objRequest.readyState>=0) {
                                  objRequest.onreadystatechange = function() { handleHttpResponse(objRequest, pElementId); };
                        'GET', pUrl, true);
                                  xmlHttpError = 'XML HTTP Request Object Unavailable';
                                  document.getElementById(pElementId).innerHTML = xmlHttpError;
                                  return false;
                              xmlHttpError = 'XML HTTP Request Object Not Supported';
                              document.getElementById(pElementId).innerHTML = xmlHttpError;
                              return false;
                      function handleHttpResponse(pObjRequest, pElementId) {
                          if (pObjRequest.readyState==4) {
                              if (pObjRequest.status==200) {
                                  // Remove the Please Wait Image
                                  for (var idx=0; idx<document.getElementById(pElementId).children.length; idx++) {
                                      el = document.getElementById(pElementId).children.item(idx);
                                      if (el.tagName == 'IMAGE') {

Open in new window

You could cut and paste the code into your page's JavaScript block, however it would be better to save that as "include.js" then add that file to your page with a script tag. Thus:

<script type="text/javascript" src="include.js"></script>

Open in new window

Now it would be unfair if I did not point out some shortcomings.  Of primary importance would be to note that if you use a language such as PHP that actually has a command or function "include" you may want to rewrite the function to be include_js. That being noted, there should not be a conflict unless you somehow, (and I'm not sure how you could do this,) mixed the JavaScript with your PHP or other server side script.

Remote scripting while available in nearly every modern browser, is not available in some browsers such as screen readers for the visually impaired and in some search engine spiders.

The code will also not work if the browser does not have JavaScript enabled. For that reason, the target HTML element can be written to contain an <IFRAME> which loads the page to be included, and we can have a <NOSCRIPT> line in the body to notify the person browsing our page that they need JavaScript enabled to achieve full functionality. Don't forget the paragraph tags inside your <NOSCRIPT> tags or your page will not validate.

                      <noscript><p>This page requires JavaScript to be supported or enabled for complete functionality.</p></noscript>
                      <p><input type="button" value="Emails.txt" name="b1" onclick="include('','theExample','images/loading_icon.gif');">&nbsp;
                      <input type="button" value="Lincoln.htm" name="b2" onclick="include('','theExample','images/loading_icon.gif');">&nbsp;
                      <input type="button" value="Movies.txt" name="b3" onclick="include('','theExample','images/loading_icon.gif');">&nbsp;
                      <input type="button" value="Latin.htm" name="b4" onclick="include('','theExample','images/loading_icon.gif');"></p>
                      <div id="theExample"><iframe name="altFrame" src="" scrolling="no" frameborder="0">Your browser does not support inline frames or is currently configured not to display inline frames.</iframe></div>
                      <script type="text/javascript">
                      // start by loading latin.htm

Open in new window

The example contains a IFRAME for browsers which do not support the remote scripting object. It also contains a <noscript> block for browsers that do not support JavaScript.

4. Conclusion

Is that all?  Just read a file?

Well no actually. You can create a select list (drop down box), or a table, and even highlight certain letters or words, see: Create Various Elements From File Data.

You can even read an external file line-by-line, see: Read A File Line By Line.

Or you can sort the file content after reading the file, see: Read And Sort A File Using JavaScript

Comments (3)

Most Valuable Expert 2011
Author of the Year 2014

Looks a lot like the foundation of AJAX, and the future of web applications in general.  Nice article, ~Ray
Author of the Year 2009

Great article!  Got my YES vote.

BTW, did you know that EE itself uses this technique extensively?  For instance, on a Zone Landing page, when you click the tabs (such as "Recent Activity", "Awaiting Answer", and "Articles") the script calls a function named AsyncInclude() to populate the listviews.  Among other things, the result is a speed up in page load (as measured by, say, Alexa) since all that "hidden stuff" does not weigh down the initial load time.
Top Expert 2005


But do they test for try - catch? LOL

Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.