Search code examples
javascriptjqueryajaxevalgetscript

run javascript external link and even internal in ajax


How many ways are to excute javascrpit code in ajaxed page ? internal and externally ... I really need to execute my scripts but found no way to my goal I tried eval in a loop & getscript method etc ... but no result is there a real way to execute my scripts ? I'm using load function to load my page please help me
I have google map it work in usual way but when I use ajax to load it, it won't work here's my code

$('ul li a').on("click",function() {
    var link = $(this).attr("href") + " #contentx";
    $('#contentx').fadeOut('slow', function(){
        $('#contentx').load(link, function(){     
            $("#mapjs").each(function(i) {
                eval($(this).text());
            });
            $('#contentx').fadeIn('slow');
        });
    });
    return false;
});

Solution

  • You'll need to move your JS block (<script id="mapjs">...</script>) into its own dedicated file.

    If you're using $.load with a landing page fragment (i.e. a URL followed by #id), then any script tags will be removed, and not executed. See the Script Execution section of the $.load documentation.

    Psuedo-code - the 'proper' way would be be something like this:

    $('ul li a').on("click",function() {
        var link = $(this).attr("href") + " #contentx";
        $('#contentx').fadeOut('slow', function(){
            $('#contentx').load(link, function(){
                if($(this).attr('href') == 'http://wearesevil.com/?page_id=16'){     
                    $.getScript('/map.js', function(){
                        $("#mapjs").each(function(i) {
                            eval($(this).text());
                        });
                    });
                }
                $('#contentx').fadeIn('slow');
            });
        });
        return false;
    });
    

    The 'hacky' way? You could change your <script id="mapjs"> to be <div id="mapjs" style="display:none;">...</div>. This wouldn't then be removed from the DOM, and you could use eval() on the text.