I'm loading a page via $.ajax() and inserting parts of the result into the corresponding parts of the page:
$.ajax({
url: '/whole_page.html',
success: function (data, status, xhr) {
$result = $(xhr.responseText);
$('#menu').html($('#menu', $result).html());
$('#content').html($('#content', $result).html());
}
});
Works like a charm, but I've run into a problem.
Now my pages contain some page-specific JS which must be executed when the result is fetched and inserted. As far as I can tell, jQuery won't return script elements if you construct a jQuery object from HTML text and query against it (I've made a fiddle to demonstrate). So, I have no way of selectively inserting only the scripts I want via jQuery.
So it would seem that I've got to pull the script elements from response text myself. Essentially, I'm looking for the right way to do this. Here's what I came up with so far:
function pullScripts(text) {
var frag = document.createDocumentFragment()
, div = document.createElement('div')
, scriptElements
;
// This is roughly how jQuery finds the scripts when cleaning text
frag.appendChild(div);
div.innerHTML = text;
scriptElements = div.getElementsByClassName('class-for-scripts-that-we-want');
$('head').append(scriptElements);
}
This works well enough, although I haven't tested it on any crappy browsers yet. Regardless, it feels uncomfortable to replicate such basic functionality of jQuery just to avoid one of its features (the special script handling). As can be seen in the fiddle, the jQuery object actually does contain the scripts, but it won't return them with something like .html() or .get(). Am I missing some obvious way of doing this?
Note: this whole topic will be moot once jQuery's internal parseHTML function is exposed
Note 2: I've also read Trying to select script tags from a jQuery ajax get response however the accepted answer is "you can't" followed by "use a regex". Both of which are unsatisfactory
$.parseHTML()method to make this easier.$.parseHTML(xhr.responseText,true)will give you a jQuery object that includes script elements. You can then extract the script tags and append or execute them after you append the html. If upgrading jQuery isn't an option, maybe you could just take the implementation of$.parseHTMLand include it as a plugin to your current jQuery.$.parseHTML()returns an array of DOM nodes, not a jQuery object. api.jquery.com/jQuery.parseHTML