Bundling with SourceURL for Dynamically Loaded Scripts

The Problem

In today’s world of large amounts of client side scripts, you may find yourself dynamically loading some of the scripts based on modularity or some other business related requirement. For example, if you give the user the option in your SPA to load up new widgets into the interface, this may require you to go and fetch the partial html for that widget alongside all the related JavaScript and Style resources required for it to run. You might utilize jquery “getScript” command to fetch this as an example. But then you jump into your Chrome dev tools to quickly find out that you cannot find that dynamically loaded script, but notice that everything is working still. Browsers do not list the dynamically loaded scripts in the source information, and as such there is no easy way to debug that script from the dev tools.

The Fix

The fix is quite simple. You need to add a tag to the end of any dynamically loaded scripts that indicates the name of that script as it should be stated in the dev tools.

Capture3

 

 

Before source URL was added (cannot find any additional scripts – just jquery-1.8.1.js):

Capture

 

 

 

 

 

 

 

 

 

 

 

 

After source URL was added (you can clearly see the “CustomScriptWithSourceUrl” in the dev tools):

Capture2

 

 

 

 

 

 

 

 

 

 

Notice the name that shows up in the dev tools is the same name you specified for the SourceURL tag.

Integrating with ASP.NET Bundling & Minification

The SourceURL tag is an easy implementation. But if your using ASP.NET Bundling and Minfication you can easily create a bundle transform that applies this logic for you automatically.

The transformation:

Capture4

 

 

 

 

 

 

 

 

 

After transformation (notice the name of the script is now the bundle path):

Capture5

 

 

 

 

 

 

 

 

 

 

Want more information on ASP.NET Bundling & Minification, and how to integrate custom bundles and transforms? Be sure to check out my latest Pluralsight course:

http://pluralsight.com/training/courses/TableOfContents?courseName=aspnet-bundling-minification-resource-optimization

Download Source Code Example

Leave a Reply