trusktr
trusktr

Reputation: 45454

Does jQuery's .load() always automatically execute scripts?

I noticed if you .load(url) and the url is a page that contains scripts, those scripts are automatically executed. Is there a way to call .load(url) without the scripts executing, then perhaps execute them later? They seem to execute even if I've used .load(url) on an element that hasn't been appended to the document.

Upvotes: 0

Views: 1139

Answers (2)

alex
alex

Reputation: 490153

jQuery's load() checks for script blocks and executes them (through its DOM manipulation helper code).

You could request the page with $.ajax() and then use the html() method to set the HTML - don't use append() as it will execute the script blocks too.

Upvotes: 2

joshschreuder
joshschreuder

Reputation: 1463

I believe you can use .get(). http://api.jquery.com/jQuery.get/

For example:

$.get('test.html', function(data) {
  // HTML text is now in data variable
  // If we use .html() the scripts are then executed.
  $('.result').html(data);
});

Also, from the .load() docs (http://api.jquery.com/load/):

When calling .load() using a URL without a suffixed selector expression, the content is passed to .html() prior to scripts being removed. This executes the script blocks before they are discarded. If .load() is called with a selector expression appended to the URL, however, the scripts are stripped out prior to the DOM being updated, and thus are not executed.

Upvotes: 2

Related Questions