Ghost
Ghost

Reputation: 63

Is it possible to .getScript from a selector?

I want $.getScript to load/execute scripts inside a div with the ID "dynamic" from "/footer.html".

$("footer").load("/footer.html #dynamic>*", function() {
  $.getScript("/assets/master.js");
});

Is it possible to load the content of a specific element (#dynamic) and load/execute scripts inside without having to separate the scripts into a different file, like the code above?

Also, why does #1 load scripts but #2 and #3 does not?

  1. $("footer").load("/footer.html"); loads entire HTML document and its scripts too.
  2. $("footer").load("/footer.html #dynamic"); loads only the "#dynamic" element and all of the content inside except for scripts.
  3. $("footer").load("/footer.html #dynamic>*"); loads only the content of "#dynamic" element but without scripts and the element itself.

I am using #3 because I want the content inside "#dynamic" without the element itself but the problem is that scripts do not load/execute.

Upvotes: 0

Views: 84

Answers (2)

Charlie
Charlie

Reputation: 23838

Is it possible to load the content of a specific element (#dynamic) with the scripts inside without having to separate the scripts into a different file, like the code above?

No. JQuery .load() method discards the scripts without execution if used with the selector expression.

So, I beleive your point 2 is not correct:

$("footer").load("/footer.html #dynamic"); loads only the "#dynamic" element and all of the content inside (scripts too).

Upvotes: 1

Amadan
Amadan

Reputation: 198436

From docs:

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