Skip to content Skip to sidebar Skip to footer

How To Dynamically Add A Javascript Function (and Invoke)

Based on a click event on the page, via ajax I fetch a block of html and script, I am able to take the script element and append it to the head element, however WebKit based browse

Solution 1:

You could try using jQuery... it provides a method called .getScript that will load the JavaScript dynamically in the proper way. And it works fine in all well known browsers.

Solution 2:

How about calling eval() on the content you receive from the server? Of course, you have to cut off the <script> and </script> parts.

Solution 3:

If you're using a library like jQuery just use the built-in methods for doing this.

Otherwise you'd need to append it to the document rather than the head like this:

document.write("<scr"+"ipt type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js\"></scr"+"ipt>");

In all honesty, I have no idea why the script tag is cut like that, but a lot of examples do that so there's probably a good reason.

You'll also need to account for the fact that loading the script might take quite a while, so after you've appended this to the body you should set up a timer that checks if the script is loaded. This can be achieved with a simple typeof check on any global variable the script exports.

Or you could just do an eval() on the actual javascript body, but there might be some caveats.

Generally speaking though, I'd leave this kind of thing up to the browser cache and just load the javascript on the page that your tabs are on. Just try not to use any onload events, but rather call whatever initializers you need when the tab is displayed.

Post a Comment for "How To Dynamically Add A Javascript Function (and Invoke)"