Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run dynamically injected javascript in DOM loaded via AJAX (attempting to ajaxify website with history.js)

I have a web application that essentially has header, footer and body views. I'm working on ajaxifying the website, using the history.js library and HTML5 pushstate, but one of the problems I'm experiencing is getting embedded javascript to run when the javascript is inserted into the DOM.

Pretty much all my javascript is wrapped in jQuery(function(){ ... }) (document on-ready loader)

Does anyone know a good strategy for dealing with this? Thanks!

like image 813
Casey Flynn Avatar asked May 23 '12 20:05

Casey Flynn


1 Answers

If I understand you, your "page" is just a container for HTML you're loading dynamically. Within that HTML you have JavaScript script blocks that currently do not execute. Is that correct? Are they in page scripts or links to new script files?

In any case, I think this answers your question: How do you execute a dynamically loaded JavaScript block?

My own thoughts:

Unless your container is incredibly generic, and so cannot know what JavaScript you might need, the simplest approach is probably to just manually attach all of your JavaScript to your container page, so that it loads with the container, perhaps minified and concatenated into a single file.

If you need to load your scripts dynamically, but you know what they are, you can do so with jQuery using .getScript() or .ajax(). I thought this page spelled things out nicely, http://www.electrictoolbox.com/jquery-dynamically-load-javascript-file/ .

Similarly, if you don't know what scripts you need until after you grab your html block, you could probably parse the html for script links and attach them manually via new script elements added to the page. As an example, the script below adds jQuery to the page if it does not already exist.

(function () {

    if (typeof(jQuery) == "undefined") {
        var headID = document.getElementsByTagName("head")[0];         
        var newScript = document.createElement('script');
        newScript.type = 'text/javascript';
        newScript.id = 'myjQuery';
        newScript.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js';
        headID.appendChild(newScript);
    }

    window.addEventListener('load', function (e)  {

        //make jQuery calls here.

    }, false);

})();
like image 91
jatrim Avatar answered Nov 20 '22 08:11

jatrim