ajax call as inline javascript code instead of document.ready for performance
For better performance i am making an ajax call , as soon as server start rendering the response. I am having the ajax call as inline in on of the dotnet user controls.
<script type="text/javascript">
// make ajax call here
$.ajax({
url: '/test.aspx',
success: function(data) {
// store the data in a global variable
}
});
</script>
I will finish the ajax call and store the value in a global variable.I am including the jquery in the master page. I don't want to make the call in document.ready as it waits for do开发者_JS百科m to be ready.Now i have the following questions.
- How can i ensure that jquery gets loaded before this inline code fires
- Is there any better way to do to gain performance as this is a client to server call
The browser will block and process
<script>
tags in the order it sees them - that's why people use$(document).ready
, to stop that from happening. If you make sure your jQuery.js is included earlier in the page than this code, you should be fine.If, rather than including that block of script inline in your .ascx control, you call
ClientScriptManager.RegisterClientScriptBlock()
to register it, you can have that script served up at the top of the page, rather than at the point where the control is included, which might potentially give a marginal increase in performance.
Edit: some extra explanation.
When processing a page, the browser will hit the <script>
tags in the order they exist in the HTML. When it does, it needs to either load the script and then run it, if the tag has a src
attribute - as your jQuery.js will - or simply run the script if it's inline JavaScript. But it must do these one at a time, in the order they're served. Have a look at this video for a visualization of this.
That's why, if your jQuery.js include comes before your inline ajax call, you don't need to worry about jQuery being loaded before your inline code fires. So don't worry about the first part of your question.
As for the second part of your question, if the ajax call is inline JavaScript in your user control, it will be somewhere in the middle of your HTML (depending on where on your page the control is included). If you use ClientScriptManager.RegisterClientScriptBlock()
, ASP.NET will inject the script at the top of the page (quite near the top of the <body>
, although after the viewstate and some other ASP.NET boilerplate) so it will be processed slightly earlier. I suspect that the difference is unlikely to be significant, though, unless your page is very large and the control is near the end of it.
Does that help?
精彩评论