5

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!

Casey Flynn
  • 13,654
  • 23
  • 103
  • 194

2 Answers2

7

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

})();
Community
  • 1
  • 1
jatrim
  • 697
  • 6
  • 10
  • I think I just found a good answer: http://api.jquery.com/jQuery.ajax/ dataType config property: ""html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM." I'm going to try it out, but this sounds just like what I need :) – Casey Flynn May 24 '12 at 06:04
  • That sounds nice and easy. Good luck! – jatrim May 24 '12 at 15:30
-1

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

osdamv
  • 3,493
  • 2
  • 21
  • 33