Jason Dentler
Jason Dentler

Reputation: 319

Script tag with type="text/html" and src="..." loaded, but ignored by jQuery

My page has a tag:

    <script id='header' src='/Templates/Shared/Header.tmpl.html' type='text/html'></script>

Firebug tells me that Firefox 5 is requesting this resource. On the HTML tab, I can navigate to the script element and see that it contains the contents of /Template/Shared/Header.tmpl.html.

jQuery, however, insists that the script tag is empty. $('#header').html() returns an empty string. I don't understand why.

Yes, I can load the file with $.get() and use $('#header').html(data) to set the contents. Then I can use it as I would expect. This obviously generates a second request, which I would like to avoid.

Upvotes: 5

Views: 6829

Answers (2)

nasskov
nasskov

Reputation: 485

This is an old problem, but still existing in Firefox. I use a workaround for it:

function getHtml(selector) {
  var $element = $(selector);
  var html = $element.html();

  if (!html ) {
    // copy all the children elements to a dummy DIV, which, unlike the SCRIPT have no problem providing the html in Firefox
    html= $('<div />').append($element.children().clone()).html();
  }
  return html;
}

Upvotes: 2

cwharris
cwharris

Reputation: 18125

I know this is old, but the answer is simple. The script tag simply does not contain any text or html.

<script id='...' src='...' type='...'></script>

There are no elements or text within the tag. The script will be requested and loaded into memory (if the script type has a handler), but the actual text itself will not be inserted into the DOM.

Upvotes: 5

Related Questions