I’m building an infinite scrolling routine that caches rows to add off-page.
I $.get the rows and add them to a $('<div/>'), then whenever I need a new row, I add one from that dom to the page.
I’ve read that when adding to the dom jquery will strip out the script tags and execute the javascript then.
This seems to be creating a problem for me as when jquery runs the script the elements are in the off-page dom, not in the main page dom.
How can I keep the script around so that it gets executed when I add an off-page element to the page?
I’ve added alerts in and the javascript never seems to get executed at all, either when adding to the off page dom, or the actual page dom, so maybe i’m failing before that becomes a problem.
Code to get new rows and place them in an off-page dom:
var nextPageDOM = $('<div/>');
var jqxhr = $.get(data.nextPageURL, function(nextPageHTML) {
nextPageDOM.html($(nextPageHTML).find(data.settings.pagedContent));
// Get the elements to add to the page
data.nextPageElements = nextPageDOM.find(data.settings.rowSelector);
}
Code to add from off-page DOM to the page:
var elementToAdd = data.nextPageElements.first().clone();
$(data.settings.pagedContent).append(elementToAdd);
It’s very difficult to solve not knowing where does many variables point, so if we suppose that data.settings.pagedContent points to the on-page DOM, why finding only the elements which equals what you already have in the ajax response?
If in the other hand data.settings.pagedContent is a selector, i’m wondering if the scripts are getting outside the selector. Would be very useful if you provide an ajaxresponse example.
Anyway, if you are looking for a way to avoid the jQuery script stripping, you can do the next:
Create a secondary div container
insert the ajax response into it via innerHTML (hope it’s well-formed)
then select the scripts from $cont and save them
Now you have extracted the scripts you can continue with your caching the same way you were doing but handling separately the html and the scripts, and in the moment you want to retrieve some html in the on-page DOM, you also append the scripts to the DOM.
Hope it helps, and sorry for asking for clarification here and not in a comment but i don’t have enough reputation.
EDIT (2013-01-22)
News in jQuery core funcionality on handling script tags parsing, implemented on jQuery 2.0 beta (jQuery 1.9 will be the last version continuing the old behavior)
from the jQuery 2.0 upgrade guide