This probably wouldn't work with the getScript functionality. The reason is that in general, items get added to the global namespace after they loaded. There is already a good discussion on this question
Based on those suggestions, you could load your script, and save the differences inside the global namespace, and when you remove the script, simply remove those object again from the global namespace.
The example here loads jQuery when you click on the button, then checks which changes were made to the global window object and upon removal, deletes those items again from the window object.
const jQueryId = "#jQuery-loaded-js-id";
function addJQuery( cb ) {
if (document.querySelector(jQueryId)) {
console.info('JQuery already loaded');
return;
}
var scriptElem = document.createElement('script');
scriptElem.id = jQueryId.substr(1);
scriptElem.addEventListener('load', function( windowKeys, e ) {
console.log( 'jQuery loaded' );
// get the difference of keys between before load and after load
// this will only work if no other scripts were loaded in between
// which would mean, scripts should only be loaded one at the time
var newKeys = Object.keys( window );
var diff = newKeys.reduce( (set, item) => {
if (windowKeys.indexOf(item) === -1) {
set.push( item );
}
return set;
}, []);
scriptElem.dataset.globalKeys = diff;
}.bind(this, Object.keys(window)) );
scriptElem.src = 'https://code.jquery.com/jquery-2.2.4.min.js';
document.body.appendChild( scriptElem );
}
function isJQueryAvailable() {
// checks if jQuery exists
alert( !!(window.jQuery || window.$) );
}
function removeJQuery() {
var elem;
if (!( elem = document.querySelector(jQueryId) )) {
console.info('not available');
return;
}
document.body.removeChild(elem);
// removes any of the global keys added to the DOM
var keys = elem.dataset.globalKeys.split(',');
for (let i = 0; i < keys.length; i++) {
delete window[keys[i]];
}
console.info('JQuery removed');
}
<button type="button" onclick="addJQuery()">Get JQuery</button>
<button type="button" onclick="isJQueryAvailable()">Does JQuery Exist?</button>
<button type="button" onclick="removeJQuery()">Remove JQuery</button>
The example shouldn't really be what you need to implement, because it oversimplifies what could happen when a script loads. Probably you need to think of a more module based approach, where the scripts you load have a way to dispose themselves. I am just giving you an example of a potential approach