Denea Novac Denea Novac - 1 year ago 120
jQuery Question

how to jQuery .load() with script tags

*I know this was answered previously using Ajax and other methods, but nothing corresponds to my needs.

I'm making a bootstrap admin theme and I'm using jQuery's .load() to avoid page refresh and have smoother transactions, though it doesn't load the script ... /script that is at the bottom of the page, it gets ignored.

I can't create a new file for each script and load it particularly, because this would mean anyone using my theme, would have to the same for the smallest scripts used for tables and so on (when they could simply be placed inside script tags), therefore it wouldn't be an usable template.

My jQuery load code:

$('.navigation .nav li a').not('.nav-item-expandable > a').click(function(navActive){
var href = $(this).attr('href');

$('.content').load('/' + href + ' .content>*');
$('.breadcrumb').load('/' + href + ' .navbar .breadcrumb>*').delay(200).queue(function(){
$('#scripts').load('/' + href + ' #scripts>*')

history.pushState('', '', href);

Lower part of my html:

<div class="content"> ... </div>

<div id="scripts">
<!-- Addons scripts -->
<script src="jquery.min.js"></script>
<script src=""></script>
<script src="addons/bootstrap/js/bootstrap.min.js"></script>
<script src="addons/toastr/toastr.min.js"></script>
<script src="addons/history.js/bundled/html4+html5/jquery.history.js"></script>

<!-- theme scripts -->
<script src="addons/theme.js"></script>

<script language="javascript" type="text/javascript">
// Icons show page
$("body .show-icons li").each(function(){
$(this).append("<a>" + $(this).attr("class") + "</a>");


Answer Source

The documentation explicitly mentions this:

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.

This thread seems to have the answer - use get instead:

$('.navigation .nav li a').not('.nav-item-expandable > a').click(function(navActive){
    var href = $(this).attr('href');

    $.get('/' + href, function(html){
        var doc = $(html);
        $('.content').empty().append(doc.find('.content > *'));
        $('.breadcrumb').empty().append(doc.find('.navbar .breadcrumb > *'));
        $('#scripts').empty().append(doc.find('#scripts > *'));
        setTimeout(function(){ breadcrumb(); }, 200);

    history.pushState('', '', href);

That will also be more efficient, since you're only making one request for the new page, rather than the three that your current script issues.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download