简体   繁体   中英

Multiple <script> tags each with its own scope

I need to programmatically generate multiple <script> tags, and each one is nearly the same except for a parameter which is different. So for example:

<script>
    function foo() { console.log('1'); }
    /* lots of very complicated code which calls foo() */
</script>

<script>
    function foo() { console.log('2'); }
    /* lots of very complicated code which calls foo() */
</script>

In this example the first script has a parameter value of '1' so its generated code prints '1' to the console, while the second script has a parameter value of '2'.

I know this question so far will offend many good programmers' sensibilities. It's of course greatly simplified and I need to do it this way for reasons beyond the scope of this question.

As I understand it, these <script> tags will share the global scope, so their foo implementations will conflict. One fix would be to name them separately, eg foo1 and foo2 . In reality I have many such functions and I'm wondering if there's a better way.

Is there a good way to enclose each <script> tag in its own scope so that the foo implementations don't conflict? I'd prefer to do this without any separate libraries or preprocessing, etc - just with native JavaScript.

I think the only way to do what you want to do is to wrap your code in a self executing function

<script>
(function () {
    function foo() { console.log('1'); }
    /* lots of very complicated code which calls foo() */
})();
</script>

<script>
(function () {
    function foo() { console.log('2'); }
    /* lots of very complicated code which calls foo() */
})();
</script>

If you do this in both instances, then it should have the desired effect. It also has the option of having both fragments in the same script tag if that is an option.

If you problem is more complex and for some reason you want to separate the namespace you can create objects.

<script>
var scope1 = (function (){
  return{
    foo: function () {console.log('1');}
  }
})();
</script>

<script>
var scope2 = (function (){
  return{
    foo: function () {console.log('2');}
  }
})();
</script>

Then (using in global scope):

scope1.foo(); //prints 1
scope2.foo(); //prints 2

I don't know all aspects of your problem, hope you find the best solution :)

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