Reputation: 1284
I need to load HTML in a div.
$("#content").load("content.html");
$("#myText").html("Prasath");
After that I need to update some text in a div(id='myText')
which is available in "content.html". "content.html" contains huge data, so it takes some time to load. Before that this line is executed:
$("#myText").html("Prasath");
How to load HTML content synchronously from JavaScript/jQuery ? I don't want to do this from call back option in load.
Upvotes: 2
Views: 3754
Reputation: 739
Please have a look on the JQuery documentation about load()
.
You can pass callback function to load()
For example:
$("#content").load("content.html", function(){
$("#myText").html("Prasath");
});
EDIT: There is no way to make load()
to load content synchronously. A workaround solution is that you can define a Jquery function that use ajax()
to send synchronous request to target url and then set the response content to destinate div.
$(function(){
$.fn.extend({
syncLoad: function (url) {
var result = $.ajax({
url: url,
async: false,
type: "GET"
}).responseText;
$(this).html(result);
}
});
$("#content").syncLoad("/echo/js/?js=hello%20world!");
});
JS Fiddle: https://jsfiddle.net/1v8fmb8b/
Upvotes: 1
Reputation: 16577
$("#content").load("content.html", function(data){
// this will execute after load is fired.
});
Use a callback.
EDIT: If you really want to make synchronous request, you can use the following code. However, you'll get a warning in console as I mentioned in the comment earlier:
var data = $.ajax({
type: "GET",
url: "content.html",
async: false
}).responseText;
// this code waits for the above ajax request.
Upvotes: 1
Reputation: 90776
You can't load it synchronously but you can quite easily do the next task in the load()
callback. For example:
$("#content").load("content.html", function() {
$("#myText").html("Prasath");
});
Upvotes: 4