I don't think this question has been posed before, at least not in the way I need it answered. I'm using jQuery's .load function. I have a problem when loading just page fragments.
When using something like:
$('#content').load('loadTest.html');
All of the scripts on loadTest.html load just fine. However, when loading page fragments like this:
$('#content').load('loadTest.html #content');
the scripts are stripped out prior to the DOM being updated
This is clearly documented in http://api.jquery.com/load/ which says:
Note: 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 however called with a selector expression appended to the URL, the scripts are stripped out prior to the DOM being updated, which is why they are never executed. An example of both cases can be seen below:
I understand that I could just externally load the script which can be used anywhere, but the thing is, I'm using a page-wide ajax system where everything is loaded dynamically. So I don't really feel like having every single javascript function that I'll ever write (100's at this point) in external files. Especially because some of these javascript functions are made from values loaded from a database which I can't account for in a .js file.
Is there any workaround for the scripts being stripped out prior to the DOM being updated? Could I in some way manually load them in? Any tiny example would be helpful to me.
Like you said. jQuery extracts that element before executing only that block.
You could modify the output to have the server return the data in a format you need, or just write your own. It would extract the elements you need them output them to the DOM.
Untested, but it would be along the lines of this..
$('#content').load('loadTest.html #content,script');
From memory this more valid..
$.get('loadTest.html',function(r){
var els = $(r).find('#content,script');
$('#content').html(els);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With