Noob Q: Different ways to run code in script tags

K

Kenny

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
 
M

Martin Honnen

Kenny said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,077
Latest member
SangMoor21

Latest Threads

Top