简体   繁体   中英

Is it possible to add JavaScript after page load and execute it

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.

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

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.

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