简体   繁体   中英

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!

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);

})();

use .on , I don't going to explain al the behavior of that function but in few words:

work through bubbling elements on the dom for example you bind "onclick" to a div you can set to some or all of his children have x behavior

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM