Last post Jan 02, 2015 02:09 PM by AidyF
Jan 02, 2015 01:55 PM|getalex|LINK
I’m reviewing some code at a client site and observed that their pages render several duplicate references to the same JS files… what happens is that they have a lot of web parts and user controls that reference some of the same common JS files.
The problem generally is observed more clearly when you drop multiple controls on the page, and more evident if you try to use the same user control or web part more than once in a page – the ideal approach would be to have some way to determine if the file
is loaded and dynamically load scripts on demand and skip duplicate calls.
I’ve been looking online without a great solution yet so I wanted to ask this community for help. Any thoughts? Feedback?
Jan 02, 2015 02:09 PM|AidyF|LINK
You could simply reference all script files once in your master page, or whatever drives your global layout. Better, you could use bundling to put all script files in a bundle.
If you really want only the relevant script files on a page then you could add the reference in code rather than in the ascx of the control.
protected void Page_Load(object sender, EventArgs e)
Page.ClientScript.RegisterClientScriptInclude(this.GetType(), "scripta", "/scripta.js");
"scripta" is the key so no matter how many times the control is added to the page the include will only be added once, so you just need a unique key for each of your include files.