Last active
August 26, 2016 12:48
-
-
Save pascalwacker/111e9b287f501a3a5940cdc13d909c4a to your computer and use it in GitHub Desktop.
jQuery.load with fragment and inline scripts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Let's asume, we try to use jQuery.load() to load a fragment of a page and have it include the inline scripts | |
*/ | |
var target = jQuery('#target'), | |
urlToLoad = '/foobar/baz.html', | |
fragment = '#wrapper'; | |
jQuery(document).on('ready', function() { | |
target.loadWithScripts(urlToLoad + ' ' + fragment, function(data, status, jqXHR) { | |
console.log('done loading `' + fragment + '` from url `' + urlToLoad + '` and executing all the scripts! (you\'re welcome ;))'); | |
}); | |
}); | |
jQuery.fn.loadWithScripts = function( url, params, callback ) { | |
var selector, response, type, | |
self = this, | |
off = url.indexOf(" "); | |
if ( off >= 0 ) { | |
selector = url.slice( off, url.length ); | |
url = url.slice( 0, off ); | |
} | |
// If it's a function | |
if ( jQuery.isFunction( params ) ) { | |
// We assume that it's the callback | |
callback = params; | |
params = undefined; | |
// Otherwise, build a param string | |
} else if ( params && typeof params === "object" ) { | |
type = "POST"; | |
} | |
// If we have elements to modify, make the request | |
if ( self.length > 0 ) { | |
jQuery.ajax({ | |
url: url, | |
// if "type" variable is undefined, then "GET" method will be used | |
type: type, | |
dataType: "html", | |
data: params | |
}).done(function( responseText ) { | |
// Save response for use in complete callback | |
response = arguments; | |
self.html( selector ? | |
// If a selector was specified, locate the right elements in a dummy div | |
// Exclude scripts to avoid IE 'Permission Denied' errors | |
jQuery("<div>").append( jQuery.parseHTML( responseText, document, true ) ).find( selector ) : | |
// Otherwise use the full result | |
responseText ); | |
}).complete( callback && function( jqXHR, status ) { | |
self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); | |
}); | |
} | |
return this; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment