ross dickinson: web and desktop software developer

Getting MVC3 to load scripts from a Partial View

by Ross on January 6, 2012 at 12:37 PM under ASP.Net | MVC | AJAX | jQuery

On an MVC3 project I'm working on, one of the things we do when allowing a user to edit a record s open up an ajax form inside a jQuery UI Dialog. This is done through a really simple setup of

  1. Call controller action.
  2. Controller action returns a PartialViewResult.
  3. Using some custom hooks into the jquery.unobtrusive-ajax library, render the partial view into a dialog.

Seems simple enough, right? This works well, except if the partial view includes script tags. By design, when using $.append, jQuery will remove all the script tags in the created element, then attempt to load them via ajax before appending the main content. This can be a problem if the script you're loading depends on elements inside the partial view's content.

Luckily, there's an easy way to get around this. When you do something like:

var newElement = $('<div><script src='somewhere'></script></div>');

jQuery doesn't return an array with one element, it actually returns with two elements!

// Assuming you have Firebug or Chrome, you can use console.debug:
console.debug(newElement.length); // This will equal 2
console.debug(newElement[0]; // This will be the main content with the script tags removed
console.debug(newElement[1]); // This will be the script tag.

So jQuery's actually nice enough to give us back everything all organized before anything happens. If you need to load the scripts after the elements have been added to the DOM, you need to manually append everything instead of just calling $.append(newElement). Here's how to do it:

// Create a parent container to hold our content. If
// you already have a parent attached to the DOM,
// you can use that instead.
var $parent = $('<div></div>');

// Create an array to hold on to our script references.
var scripts = [];

// Append any elements that aren't scripts,
$newElement.each(function() {
	var el = $(this);
	// tagName is always all caps.
	if (el.prop('tagName') === 'SCRIPT') {
	else {

// If your parent element isn't attached to the DOM yet, you need to do
// that now before adding the scripts, otherwise any scripts that reference
// elements from the html fragment will fail.


// Now we just need to append each script from our scripts array.
// jQuery does this synchronously so the scripts will still load
// in the same order they were originally in.
$(scripts).each(function(i, script) {

TIP: Because your new elements will be displayed before your scripts are loaded, you should consider hiding them before the scripts are appended, and then show them afterwards.

Add comment

  • Comment
  • Preview

About the author

rossisdead is a 26 year old web and desktop software developer from New Jersey. He has two cats and likes long walks on the beach.

On Stackoverflow

On Stackoverflow Careers

On Codeplex

On Github