I would like to implement an AJAX-based navigation which falls back gracefully when JS is not available and want to do it on top of existing pages. In order to attain this I will ad a 'container' div which:
- marks the part of the page which need to be replaced
- contains all the scripts that need to be inserted into the page
What I want to do is basically use AJAX to:
- replace the content of div#main
- execute all the script contained within div#main after replacing the div
- do NOT execute other scripts contained in the page download using AJAX
Basically something like this:
<html>
... menu, navigation, borders, social etc...
... come scripts which must NOT be executed when using AJAX page load ...
<div id="main">
... main HTML which needs to be replaced in page ...
<script> ... scripts which need to be executed ... </script>
</div>
... footer, copyright, links etc...
</html>
I know from the manual that the following will NOT work:
$('#main a').click(function() {
$('#main').load( $(this).attr('href')+' #main' );
})
because the CSS selector will cause filtering out all the scripts. So I tried using $.ajax and processing the code below.
$.ajax( $(this).attr('href') ).done( function(data) {
$('#main').replaceWith( $(data).find('#main') ); // .1
$(data).find('#main').filter("script").each(function() {
eval( $(this).text() ); // .2
alert( $(this).text() ); // .2
});
})
which does NOT work either.
- .1 will insert the main DIV but will not insert any SCRIPT
- .2 will never be executed
to my best understanding $(data) should not filter out scripts but the trial of facts shows this does not work
So far my only solution (or perhaps should we call it workaround?) is to use regex-based parsing of the 'data' string but I don't really like that and would like a more robust and standard based solution.
P.S.: the existing environment is using JQuery 1.7 but I believe we can easily upgrade
P.P.S.: I understand that the above works only for links and not for forms but this is enough for my use case