Noob Q: Different ways to run code in script tags

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Kenny

    Noob Q: Different ways to run code in script tags

    I found some code in a sample web page that ends like this:


    .....

    <script>
    (function () {...good stuff here...})();
    </script>
    </body>
    </html>

    So it builds an anonymous function and immediately invokes it. Fine.

    Now I see on another page:

    <script>
    ....good stuff here...
    </script>

    So... what's up with that? I guess it is a two-part question:

    1. What is the difference?

    2. When is either preferred?

    I can see maybe the anonymous function would have different scope, or
    maybe avoid polluting the global namespace. I imagine it also runs
    closer together in time because the whole thing gets parsed and then
    dispatched all at once.

    Am I getting warm?

    kt
  • Martin Honnen

    #2
    Re: Noob Q: Different ways to run code in script tags

    Kenny wrote:
    I can see maybe the anonymous function would have different scope, or
    maybe avoid polluting the global namespace.
    Avoiding polluting the global namespace is the main reason I think.

    --

    Martin Honnen

    Comment

    Working...