简体   繁体   中英

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?

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 */ };

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

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)

put it in an anonymous function:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM