Skip to content

When loading an html page via ajax, will script tags be loaded?

When you load an html document using AJAX, what does it do with the nodes inside the HEAD tag: (script,link,style,meta,title) ignore them or load and parse them? And in the case of jquery ‘s ajax() function?

Answer

When you call the jQuery.ajax() method, you can specify the dataType property, which describes what kind of data you are expecting from the server, and how to handle it once it is received.

By default, jQuery will try to guess the dataType based on the MIME type of the response. However you can explicitly specify a dataType from the following:

  • html: Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.

  • text: A plain text string.

  • xml: Returns a XML document that can be processed via jQuery.

  • script: Evaluates the response as JavaScript and returns it as plain text. Disables caching unless option “cache” is used.

  • json: Evaluates the response as JSON and returns a JavaScript object.

  • jsonp: Loads in a JSON block using JSONP. Will add an extra “?callback=?” to the end of your URL to specify the callback.

As an example, the following ajax call will return the data as a plain text string, without executing the scripts or manipulating the DOM:

$.ajax({
  url: 'ajax/test.html',
  dataType: 'text',
  success: function(data) {
    alert(data);
  }
});