0

I am creating a little Javascript frontend framework. I decided to optimize it for HTTP 2 -> no bundling.

I have asynchronous dependency loader, that on-demand (in browser) loads all needed resources for the given page.

But there's a little problem. Lets say that application programmer wants to use jQuery. I append script tag with jQuery to the body.

From what I understand, all libraries hosted on a cdn does use UMD. And since I don't use either AMD, Common JS, nor ES6 import, it exposes jQuery variable to my application global scope.

But I dont want to polute global application scope with that variable. Instead, I want to be able to rename that variable, and possibly add it to the given namespace.

Is it possible?

One solution I was thinking of was loading that script with XHR request, use eval() on it and somehow wrap the result in my framework's code. But I am kinda lost, and have no idea how to do that.

Thanks for any advice.

Matúš Čongrády
  • 1,340
  • 3
  • 17
  • 29

1 Answers1

1

We can achieve this by including script through XHR.

var myObj = {};
var myOverride = function(res){
  var jqRes = res.currentTarget.responseText;
  console.log(res.type);
  eval(jqRes);
  myObj.jq = $;
  $ = undefined;
  console.log(myObj.jq);
}
var xhr =  new XMLHttpRequest();
xhr.open("GET","https://code.jquery.com/jquery-2.2.3.js");
xhr.addEventListener("load",myOverride);
xhr.send();

Please find the attached JSFiddle. https://jsfiddle.net/h9aycg6m/

But my suggestion would be not to override these variables as $ / jQuery are terms are already in global reach.

Bkjain655
  • 200
  • 6