Reputation: 1173
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
Reputation: 766
put it in an anonymous function:
(function(){
// >Your code goes here<
})();
Upvotes: 0
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
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.
And: JavaScript Namespace
Upvotes: 0
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