Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery AJAX call - how to keep comments

Tags:

jquery

ajax

context: For the development version of a JavaScript project I wrote a small utility to keep track of scriptfile dependencies (because I don't like any of the existing libraries' hilarious syntax requirements). I wanted to make it work in a way similar to other languages, so I decided to parse imported files for comments like this:

// DEPENDS: myurl.js //

to build and evaluate dependency graphs and fetch dependencies using jQuery's $.ajax(). This works well with top-level files. Files loeded with the ajax-call, however, get stripped of comments, so I can not parse the dependencies further.

For your interest: The cycle is

  1. fetch file
  2. parse content with regex for dependencies
  3. extend dependency graph if neccessary
  4. start from (1), if (3) happened (with required files, of course)
  5. evaluate files' script content in order

question: Is there a way to stop jQuery from removing JavaScript comment tags from files loaded by $.ajax()?

code: I am calling ajax this way

$.ajax({
  url: fileName,
  dataType: 'text',
  context: this,
  success: function(jqXHR) {
    this.parseImport(fileName, jqXHR);
  }
});

(from inside a method providing fileName and this properly). I was hoping dataType: 'text' would force jQuery to import text literally, but, well, it didn't :-D

The API document for $.ajax() tells, that the content of dataType: text elements gets parsed with window.String, but I'm not sure, what window.String does to its input. Maybe the solution is somewhere in this part?

I'd be glad if anybody could point me in the right direction.

like image 226
waechtertroll Avatar asked May 07 '15 08:05

waechtertroll


1 Answers

The way you're using ajax will not strip comments from the file. You're asking jQuery to load text from the server. It will load that text, faithfully, without modifying it in any way. I suspect you have some minification/compression process in place at the server end that removes comments. That jQuery code won't.

But you can still get around whatever it is that's removing comments — by not using comments. You can use a string instead:

"DEPENDS: myurl.js";

Since that's not a comment, it shouldn't get stripped. It looks a bit odd at first, but JavaScript's syntax has ExpressionStatement, which is a statement consisting entirely of an expression. And of course, a string literal on its own is a valid expression. (This is how they did "use strict"; in ES5 without it causing a problem for pre-ES5 JavaScript engines.)

like image 183
T.J. Crowder Avatar answered Sep 19 '22 15:09

T.J. Crowder