5

Suppose I've to attach some content to the page dynamically and it involves some HTML and some Javascript (by adding more script tags).

How do I know everything is ready (just like on page load I would do with jQuery $(..) )?

Or is it just fine to go on after the append operation completes?

gotch4
  • 13,093
  • 29
  • 107
  • 170
  • You have to use like this $(document).ready(function(){}); The ready event occurs when the DOM (document object model) has been loaded. – Balachandran May 14 '14 at 11:25
  • Refer this http://stackoverflow.com/questions/4584373/difference-between-window-loadfunction-and-document-readyfunction – Dipak May 14 '14 at 11:27
  • show your code us which was you tried – Balachandran May 14 '14 at 11:32
  • 2
    I could be wrong but I believe `.append()` is synchronous, so its fine to work with the dynamic content afterwards – billyonecan May 14 '14 at 11:36
  • Turns out you are right -> http://stackoverflow.com/questions/5085228/does-jquery-append-behave-asynchronously thank you very much – gotch4 May 14 '14 at 14:08

1 Answers1

0

I have had luck including a ready function within the appended HTML. For instance

var new_html = "<SCRIPT>$(function() { alert("ready!");});</SCRIPT> <DIV>Added content</DIV>";
$("#host-div").append(new_html);

After the new div is appended, the script will run. I usually use this technique to initialize jqueryui widgets in added content. This is especially useful when using AJAX to get the HTML from the server, and the HTML is generated from a template file - it keeps the logic at the HTML/presentation level and in the same code module.

Roger Kaplan
  • 307
  • 1
  • 2
  • 11