0

Say I have a JavaScript function that is inserted into the page after page load how can I then call that function. For example lets keep things simple. Say I make an Ajax call to get the markup of the script and the following is returned:

<script type="text/javascript">
function do_something() {
    alert("hello world");
}
</script>

If I then add this markup to the DOM can I call do_something() later?

I'm use the jQuery JavaScript framework.

3 Answers 3

3

You could use the $.getScript(...) function of jQuery. Most often this meets the need for loading JavaScript asynchronously after the page has been loaded.

Here are the according docs: http://api.jquery.com/jQuery.getScript/

Basically you can do something like

$.getScript("http://myhost.com/scripts/myscript.js", function(){
   //at this point the script has been attached to the page and processed
   //you can use it here
});
Sign up to request clarification or add additional context in comments.

Comments

2

Update Sorry, I missed that you were using jQuery. You can just do this with the string you're getting back:

$(str).appendTo(document.body);

...after which you can call do_something immediately; live example.


Original answer:

If you're in control of the other end (the part receiving the ajax call), just have it reply with straight JavaScript code, and instead of ajax use a script element:

var script = document.createElement('script');
script.src = /* ...your URL...*/;
document.body.appendChild(script);
do_something();

The script is parsed and executed as soon as you append it to the document, as you can see from the above where I've happily called do_something immediately after doing the appendChild.

It's also possible to add the script text inline if you prefer.

Comments

0

Just use $('head').append('<script>...') to add the script to the page. jQuery has special routines for handling this and parsing the script tags and handling them appropriately for all browsers.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.