Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Webforms, JavaScript in user controls

We are struggling a little regarding the right implementation of JavaScript in our solution (APS.NET Webforms).

We want to have all (or at least as much as possible) of our javascript at the bottom of pages, according to best practice, so pages load HTML and CSS first and give a better user experience.

There is a lot of jQuery code throughout our project that is often specific to certain controls, so we don't want that to load on every page.

Currently jQuery itself, including jQuery UI are positioned at the top of pages, so that we can have jQuery usages in controls (either from js files or sometimes inline code), however, we want to move all that stuff down to the bottom of the page. We have already added a contentplaceholder ("JavascriptFooter") at the bottom of the page, so we can place javascript from pages in the footer of the page, but we're stuck on the controls.

What are best practices for this? Should we externalize all JS and in the JS check if a control is loaded? But then we will be showing too much stuff all the time. Or is there another way?

like image 205
Richard Avatar asked Sep 06 '12 15:09

Richard


1 Answers

First, I would suggest loading Jquery from a CDN. Here is the code for Google:

<script type="text/javascript">
    document.write(["\<script type='text/javascript' src='", 
    ("https:" == document.location.protocol) ? "https://" : "http://", 
    "ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'>\<\/script>"].join(''));
</script>

That way, if the visitor has been served this on another site, it will already be cached. In addition, it will download in parallel as it is being delivered from a different host.

I also agree with @ctorx - you should use document ready execution.

In addition, you could use a ScriptManager and create all your control specific JS in the code behind of each control (probably a good idea anyways if that control is the only object utilizing that JS) - all this code renders at the bottom of the page.

Example:

Page pg = (Page)System.Web.HttpContext.Current.Handler; // or this.Page in .ascx
ScriptManager.RegisterStartupScript(pg, typeof(Page), "myJS", "[... your code ]", true);
like image 144
CoderMarkus Avatar answered Sep 17 '22 13:09

CoderMarkus