[英]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. 我正在使用javascript库,但由于我在这个大站点上有其他库,因此似乎无法使用。 Is there a way I can sandbox it somehow? 有什么办法可以将其沙盒化吗? perhaps putting it in an iframe then assigning a var in my javascript class as 也许将其放在iframe中,然后在我的javascript类中分配一个var为
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? 如何在Javascript库中沙箱化并访问它?
This is why we practice keeping vars out of the global scope. 这就是为什么我们尝试将var排除在全局范围之外。 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';
请记住,这只会修复显式声明的变量,例如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
. 但不会修复隐式声明的变量,例如foo = 'bar'
,该变量仍将分配给全局对象,最有可能是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. 将其放入iframe中肯定会阻止其正常工作。 All you can do is wrap the offending code in a function so everything runs within the scope of that function. 您所能做的就是将有问题的代码包装在一个函数中,以便一切都在该函数的范围内运行。
See: Javascript Namespacing 请参阅: Javascript Namespacing
And: JavaScript Namespace 并且: JavaScript命名空间
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<
})();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.