BruteCode
BruteCode

Reputation: 1173

How do I sandbox a JS lib?

I am using a javascript lib and it seems to be failing because of my other libs on this big site. Is there a way I can sandbox it somehow? perhaps putting it in an iframe then assigning a var in my javascript class as

var myvar = iframe.theJSlib;

I'm just writing an idea. I don't know how to sandbox nor if it could be done. How do I sandbox a javascript lib and access it in my main page?

Upvotes: 1

Views: 113

Answers (4)

Erick Ribeiro
Erick Ribeiro

Reputation: 766

put it in an anonymous function:

(function(){
    // >Your code goes here<
})();

Upvotes: 0

PitaJ
PitaJ

Reputation: 15012

You can't just sandbox one lib at a time. You have to sandbox them all by running them in compatibility mode in their own namespaces:

(function(myLib){
    // do stuff with this lib here
})(theLongLibname)

Upvotes: 0

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114367

Putting it in an Iframe would certainly stop it from working properly. All you can do is wrap the offending code in a function so everything runs within the scope of that function.

See: Javascript Namespacing

And: JavaScript Namespace

Upvotes: 0

SeanCannon
SeanCannon

Reputation: 77966

This is why we practice keeping vars out of the global scope. Try to either enclose everything in the lib in its own function, like so:

(function(){
  // the library code
}());

Keep in mind this will only fix explicitly declared variables like var foo = 'bar'; but will NOT fix implicitly declared variables like foo = 'bar', which will still be assigned to the global object, most likely window.

You can also try to change all your code to use a single namespace like so:

var myApp = {};

myApp.foo = { /* maybe my validator code */ };
myApp.bar = { /* maybe my utilities code */ };

Upvotes: 1

Related Questions