Same variables in different '<script>' tags without them clashing?

920 views Asked by At

I want to use same variables in different <script> code blocks without them clashing. My code looks roughly like this:

<html>
<head>
    <script type="text/javascript">
        ad = document.getElementById('sidebar1-ad');

        if (ad.getBoundingClientRect().width) {
            adWidth = ad.getBoundingClientRect().width;
        } else {
            adWidth = ad.offsetWidth;
        }

        ...
    </script>

    <script type="text/javascript">
        ad = document.getElementById('article-footer-ad');

        if (ad.getBoundingClientRect().width) {
            adWidth = ad.getBoundingClientRect().width;
        } else {
            adWidth = ad.offsetWidth;
        }

        ...
    </script>
</head>

<body> ... </body>
</html>

The problem is, variables ad and adWidth in the second code block seem to take precedence.

Is there a way I can use the same variable names in different <script> tags in a page without any one overwriting the other? If so, how?

2

There are 2 answers

2
Olegas On BEST ANSWER

If you can change you script body, just wrap your code to an anonymous function and call it immediately. Also, you need to use var keyword to limit variable scope.

<script>
  (function() {

      var ad = document.getElementById('article-footer-ad');

      // your code here ...

  })(); // <-- this is an immediate call
</script>

Also, if code in every block is the same, consider refactoring it to a single function and use in other code blocks

<script>
    // Common function

    function renderAd(adId) {

        var ad = document.getElementById(adId);

    }
</script>
...
<script>
    renderAd('sidebar1-ad');
</script>
...
<script>
    renderAd('article-footer-ad');
</script>
1
Joe Enzminger On
<html>
<head>
<script type="text/javascript">
(function()
{
    var ad = document.getElementById('sidebar1-ad');

    if (ad.getBoundingClientRect().width) {
        var adWidth = ad.getBoundingClientRect().width;
    } else {
        var adWidth = ad.offsetWidth;
    }

    ...
})();
</script>

<script type="text/javascript">
(function()
{
    var ad = document.getElementById('article-footer-ad');

    if (ad.getBoundingClientRect().width) {
        var adWidth = ad.getBoundingClientRect().width;
    } else {
        var adWidth = ad.offsetWidth;
    }

    ...
})();
</script>

...