最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Is it possible to add JavaScript after page load and execute it - Stack Overflow

programmeradmin1浏览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.

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.

Share Improve this question edited Oct 15, 2011 at 11:01 Yi Jiang 50.2k16 gold badges139 silver badges136 bronze badges asked Oct 15, 2011 at 10:57 geoffs3310geoffs3310 14k24 gold badges67 silver badges86 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 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./jQuery.getScript/

Basically you can do something like

$.getScript("http://myhost./scripts/myscript.js", function(){
   //at this point the script has been attached to the page and processed
   //you can use it here
});

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.

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.

发布评论

评论列表(0)

  1. 暂无评论