Let’s do code first:
$(function(){
//Step-2) Load and a template from server and APPEND to BODY
function loadTemplate(path, callback) {
$.get(path, null, function (t) {
$('body').append(t);
}, 'text');
if (callback != undefined && typeof (callback) == 'function') {
callback.apply(window);
}
}
//Step-3) a callback method
function showProduct() {
//setTimeout(function () {
// $('#prodBasicView').tmpl(prod).appendTo('#prodView');
//}, 100);
alert($('#prodBasicView').length); // it alerts 0, But I am expecting 1
}
//Step-1) initiating loading template
loadTemplate('/template/remote-template2.htm', showProduct);
});
remote-template2.htm :-
<div id="prodBasicView" style="display:none;">
<div class="myProd">
<h3> Product Name</h3>
<span>Price: $ 700 </span>
</div>
</div>
ISSUE:
- loadTemplate method successfully loaded a template (remote-template2.htm) and append to body.
- After successfully loaded the template the passing callback function showProduct method get fired.
- Inside showProduct method I am trying to use loaded template ($(‘#prodBasicView’)) but it returns empty array.
- But if I delay the execution of showProduct with few millisecond it works but I don’t think its a good practice
-
The above point seems to be appended DOM elements are not ready
-
HOW TO MAKE SURE MODIFIED/ MANIPULATED DOM IS READY AGAIN BEFORE USING THEM ??
It seems to me that you just need to put the callback-calling code within the
$.getcallback, like so: