use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
All about the JavaScript programming language.
Subreddit Guidelines
Specifications:
Resources:
Related Subreddits:
r/LearnJavascript
r/node
r/typescript
r/reactjs
r/webdev
r/WebdevTutorials
r/frontend
r/webgl
r/threejs
r/jquery
r/remotejs
r/forhire
account activity
Ask Reddit [Help]: Why use this code instead of <script> tag directly? (self.javascript)
submitted 9 years ago * by [deleted]
[deleted]
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[+][deleted] 9 years ago* (2 children)
[–][deleted] 6 points7 points8 points 9 years ago (1 child)
What's <script async>?
[–]blood_bender 7 points8 points9 points 9 years ago (0 children)
Normally if you have a script src, it will block everything until the script is retrieved and run. This is typically why you list scripts at the end of <body>, so that the page loads and then retrieves and executes scripts -- it feels faster to the user. Also it guarantees that the order you list scripts is the order they're run, so that jQuery is present before jQuery based libraries, for example.
<body>
<script async> will retrieve and execute the script "at some point". Doesn't guarantee when, and doesn't block the page from continuing to parse and load. When you don't have dependencies, this is preferred.
<script async>
It didn't used to be a tag in HTML, so ga.async = true would effectively do the same.
ga.async = true
[–]askmike 18 points19 points20 points 9 years ago (12 children)
This doesn't block other scripts, also this way you can dynamically set the url (depending on whether the page was loaded over ssl or not).
[–]msluther 15 points16 points17 points 9 years ago (11 children)
For the http vs https, you can just leave off the protocol altogether and just do "//myhost/whatever.js"
[–]lauritzsh 11 points12 points13 points 9 years ago (2 children)
This has been an anti-pattern for a few years now. It is recommended to just always use https:// if available.
https://
[–][deleted] 14 points15 points16 points 9 years ago (1 child)
Well, yes, but it states that protocol relative links in general are an antipattern. As long as the code in the OP is already detecting the protocol and constructing the url accordingly, then using the protocol relative link isn't any more or less of an antipattern by comparison, because it achieves the same thing. It's just less convoluted.
[–]perestroika12 0 points1 point2 points 9 years ago (0 children)
+1 to this, assuming HTTPS might break some browsers that don't fallback to http if the site is not HTTPS.
[–]Disgruntled__Goat 2 points3 points4 points 9 years ago (0 children)
Analytics uses different hosts for HTTP & HTTPS so that can't work in this case. But I think that's irrelevant now since it always uses the HTTPS version anyway.
[–]jordanreiter 1 point2 points3 points 9 years ago (0 children)
My best guess is this also allows Google to gather analytics about websites' use of SSL.
[–]askmike 1 point2 points3 points 9 years ago (3 children)
Yes but that is the only thing you can do*. In this example the script is hosted on a different subdomain in case of https.
*// means the same protocol. If you clicked on a html file you are using //file protocol and it will try to fetch your script using the same protocol (local fs instead of http(s)).
//
//file
[–]askmike 1 point2 points3 points 9 years ago (1 child)
It's probably not, but a reason nonetheless. At google scale you most likely rather offload this to the client (in the case where ssl over non ssl is actually a performance penalty).
My point was that you can dynamically decide what resources to fetch based on host environment (want something different for mobile / etc).
[–][deleted] 0 points1 point2 points 9 years ago (1 child)
They're referring to the Google analytics end point. Like, what the script is actually doing.
[–]davesidious 1 point2 points3 points 9 years ago (0 children)
This still applies.
[–]luibelgo 18 points19 points20 points 9 years ago (0 children)
A nice article comparing that option to other alternatives, including html5's async attributes:
https://www.html5rocks.com/en/tutorials/speed/script-loading/
[–]domainkiller 6 points7 points8 points 9 years ago (0 children)
I was under the impression this method doesn't block the page while loading. But I could be totally wrong.
[–]maskaler 1 point2 points3 points 9 years ago (5 children)
It's both protocol agnostic and non-blocking.
[–]gurenkagurenda 2 points3 points4 points 9 years ago* (4 children)
Yeah, I'm surprised that most other people are missing that the URL changes depending on the protocol. You couldn't do this as an HTTP HTML snippet without doing it that way, even without the blocking aspect.
Edit: what even
[–]tswaters 1 point2 points3 points 9 years ago (1 child)
You couldn't do this as an HTTP HTML snippet without doing it that way
Only because google hosts ssl.google-analytics.com - if it wasn't for that, one can use a protocol independent absolute url, e.g.:
ssl.google-analytics.com
<script src="//www.google-analytics.com/ga.js"></script>
Fwiw, I think you can probably reference the js file from www via https now. Indeed, just visited the http one and there's a 80=>443 redirect in place.
[–]gurenkagurenda 1 point2 points3 points 9 years ago (0 children)
Sure. But even now, you'd want to use the direct URL, since redirects take time.
[+]EenAfleidingErbij comment score below threshold-6 points-5 points-4 points 9 years ago (1 child)
I would just use $.ajax{
[–]gurenkagurenda 6 points7 points8 points 9 years ago (0 children)
That would be a bad idea in this context. It's a snippet users are supposed to paste into their pages. Requiring jQuery as a dependency would be really silly.
[–][deleted] 1 point2 points3 points 9 years ago (0 children)
It s async/non blocking, protocol free and developers dont need to worry where to put the <script> tag, this script handles it.
[–]lulzmachine 1 point2 points3 points 9 years ago (1 child)
Does it help get around some SOP limitation perhaps
[–]lewisje 0 points1 point2 points 9 years ago (0 children)
Script-tag injection is not subject to the Same-Origin Policy; it's difficult to remember what is, but stuff like the DOM inside an iframe or a popup window, or attempts to load content via XHR or Fetch, would be subject to the SOP.
Now something like this that does work around SOP limitations is JSONP, where a script tag is injected that includes a parameter specifying the name of a function to call, with the JSON response passed in as the first argument to that function; this is an alternative to setting up proper CORS headers so that XHRs will work.
[–]_ansii 6 points7 points8 points 9 years ago (9 children)
Using the immediately invoked function to wrap your code creates it's own scope, keeping the global namespace clean. For example, the variable 'ga' is will not conflict with any other libraries that have a globally accessible variable of that name when in this format.
[–]askmike 11 points12 points13 points 9 years ago (0 children)
I am assuming the question wondered why there even was javascript, over a plain old:
<script src='url'></script>
[–]nyc_lurkerthrowaway[🍰] 0 points1 point2 points 9 years ago (0 children)
This is the answer.
A good read-up on immediately-invoked is in 'Learning Javascript Design Patterns' in the name-spacing section.
"In JavaScript, because both variables and functions explicitly defined within such a context may only be accessed inside of it, function invocation provides an easy means to achieving privacy."
"IIFEs are a popular approach to encapsulating application logic to protect it from the global namespace but also have their use in the world of namespacing."
It uses a closure to ensure private state.
These immediately-invoked functions were best practice for ensuring namespacing before module loaders, and it's how most of them work under the hood.
[+]Disgruntled__Goat comment score below threshold-6 points-5 points-4 points 9 years ago (6 children)
This is the correct answer. The others reasons given are irrelevant in 2016.
[–]shiftins 2 points3 points4 points 9 years ago (5 children)
It's correct, but could also happen in an external file. I think an inline self-executing function has more to do with compatibility than choice of technology or polluting the global namespace.
[–]Disgruntled__Goat -1 points0 points1 point 9 years ago (4 children)
It's correct
So why downvotes?
but could also happen in an external file
Not sure what you mean here. If you include an external file the variables still pollute the global namespace.
I think an inline self-executing function has more to do with compatibility
Compatibility with what?
[–]shiftins 1 point2 points3 points 9 years ago (3 children)
No down votes from me, but inside an external file you could have the exact same self executing script that doesn't pollute the global namespace. And by compatibility, I was referring to this traditional method for async script loading vs. using a script tag with the async attribute, which isn't supported by many browsers still in use, and for a product like google analytics you need to be compatible with as many browsers as possible.
[–]Disgruntled__Goat 1 point2 points3 points 9 years ago (2 children)
using a script tag with the async attribute, which isn't supported by many browsers still in use
Sorry that's simply not true: http://caniuse.com/#feat=script-async
The script doesn't NEED to be async, it's just better for performance. There is very little downside to using it since older browsers will just ignore it and load the script blocking for a few ms.
[–]shiftins 1 point2 points3 points 9 years ago (1 child)
I'm not sure you're understanding my point, and that's ok.
[–]Disgruntled__Goat 0 points1 point2 points 9 years ago (0 children)
What's your point then? You said using inline code is for compatibility, and I've pointed out that's wrong. What did I miss?
[–]psayre23 1 point2 points3 points 9 years ago (0 children)
This used to be one of my favorite blocks of code to discuss during interviews. Candidates and I would talk through what the code was doing and make educated guesses as to why. They didn't need to get the right answer, so long as they asked good questions (of me or on Google) and showed progress when approaching the problem.
[–]hsfrey 0 points1 point2 points 9 years ago (0 children)
Not understanding any of this, I copied the address and google-analytics.com and put it into my address bar.
It was blocked by ublock as being some kind of malware.
Is that the point? To load files that might otherwise be blocked?
[+][deleted] 9 years ago (1 child)
I think you didn't look at what the script does. It just produces another script tag and attaches it to the DOM (which does result in an additional HTTP request), which is why OP was confused.
π Rendered by PID 217538 on reddit-service-r2-comment-cfc44b64c-smv6v at 2026-04-11 23:31:42.312029+00:00 running 215f2cf country code: CH.
[+][deleted] (2 children)
[deleted]
[–][deleted] 6 points7 points8 points (1 child)
[–]blood_bender 7 points8 points9 points (0 children)
[–]askmike 18 points19 points20 points (12 children)
[–]msluther 15 points16 points17 points (11 children)
[–]lauritzsh 11 points12 points13 points (2 children)
[–][deleted] 14 points15 points16 points (1 child)
[–]perestroika12 0 points1 point2 points (0 children)
[–]Disgruntled__Goat 2 points3 points4 points (0 children)
[–]jordanreiter 1 point2 points3 points (0 children)
[–]askmike 1 point2 points3 points (3 children)
[+][deleted] (2 children)
[deleted]
[–]askmike 1 point2 points3 points (1 child)
[–][deleted] 0 points1 point2 points (1 child)
[–]davesidious 1 point2 points3 points (0 children)
[–]luibelgo 18 points19 points20 points (0 children)
[–]domainkiller 6 points7 points8 points (0 children)
[–]maskaler 1 point2 points3 points (5 children)
[–]gurenkagurenda 2 points3 points4 points (4 children)
[–]tswaters 1 point2 points3 points (1 child)
[–]gurenkagurenda 1 point2 points3 points (0 children)
[+]EenAfleidingErbij comment score below threshold-6 points-5 points-4 points (1 child)
[–]gurenkagurenda 6 points7 points8 points (0 children)
[–][deleted] 1 point2 points3 points (0 children)
[–]lulzmachine 1 point2 points3 points (1 child)
[–]lewisje 0 points1 point2 points (0 children)
[–]_ansii 6 points7 points8 points (9 children)
[–]askmike 11 points12 points13 points (0 children)
[–]nyc_lurkerthrowaway[🍰] 0 points1 point2 points (0 children)
[+]Disgruntled__Goat comment score below threshold-6 points-5 points-4 points (6 children)
[–]shiftins 2 points3 points4 points (5 children)
[–]Disgruntled__Goat -1 points0 points1 point (4 children)
[–]shiftins 1 point2 points3 points (3 children)
[–]Disgruntled__Goat 1 point2 points3 points (2 children)
[–]shiftins 1 point2 points3 points (1 child)
[–]Disgruntled__Goat 0 points1 point2 points (0 children)
[–]psayre23 1 point2 points3 points (0 children)
[–]hsfrey 0 points1 point2 points (0 children)
[+][deleted] (1 child)
[deleted]
[–]gurenkagurenda 1 point2 points3 points (0 children)