Reputation: 624
So I understand that when script tags are executed it's in the global scope, I was wondering if there was any way to make them execute in a local scope. For example:
function scoped() {
const scopedVariable = '10';
const scr = document.createElement('script');
scr.src = '//cdn.blabla.com' //third party script
document.body.appendChild(scr);
}
What I want is for the code that's executed in the script to have access to the scopedVariable
. Meaning, I want the script to be executed within the scoped()
execution context.
Upvotes: 3
Views: 623
Reputation: 1074495
You have two options in modern environments:
Use a module. That's a type="module"
script
tag on browsers. Modules have their own scope, like a function call does. (They also have the benefit of defaulting to strict mode, and being deferred by default so they don't execute until the HTML parsing is complete.) If you have to support browsers that don't support modules (such a IE11), you can use bundlers like Webpack or Rollup.js.
Use a function call — e.g., a wrapper function, like this:
(() => {
// Your code here
})();
Other than #1 above, you can't change the scope that the code at the top level of a script loaded via a script
tag runs in.
#2 works in older environments as well, if you use a traditional function instead of an arrow function.
Upvotes: 3