So i have been building a website for quite some time for a client and they are getting several javascript operations per page. So i decided to stream line this generation of the javascript material (this includes ajax content, ui manipulation and parsing). So i have a script producer in PHP that will generate scripts in a specific order, this way there is no risk of doing operations that are not ready yet*.
SO then i got into this weird little conundrum. Is there any efficiency in producing scripts like this...
<script type="text/javascript">
script1.action();
script1.secondAction();
script2.action();
...
scriptN.action();
</script>
or
<script type="text/javascript">script1.action()</script>
<script type="text/javascript">script1.secondAction()</script>
<script type="text/javascript">script2.action()</script>
<script type="text/javascript"> ... </script>
<script type="text/javascript">scriptN.action()</script>
Thank you for your input.
* Obviously there can always be some inherent risk no matter how "Safe" you try to program.
-
possible duplicate of multiple versus single script tagsJames Montagne– James Montagne2012年02月28日 22:32:15 +00:00Commented Feb 28, 2012 at 22:32
3 Answers 3
Either way, both the tags and the contents within are going to be executed sequentially - no need to worry there.
It would be good to go with the first option if possible, however. Each time a browser comes to a tag, it will stop rendering until it has time to hand the code off to a javascript interpreter and get the results.
Unless you have many different scripts, or very large scripts, this delay will not likely be noticed by any end users. As James mentioned, though, it will also result in a slightly slower load time and heavier server load simply because it is more characters.
Comments
More characters = larger file size = slower load time.
There is likely slight overhead in parsing the tags separately as well.
Definitely go with the first approach.
Comments
It seems your question is with regards to over-use of the inline script tag.
When a browser encounters a tag, it parses the text, in-between the tags, sends the text to the browsers javascript engine, waits for an output back and continues on. So, in theory, increasing the number of script tags would increase your load times, but how negligible or important is that for you, is it worth working a bit harder for a fix?
Personally, I would not be able to handle the stress of knowing my browser is doing more than it should. Aside from the fact that the html will be hard to maintain, read. I am against coupling javascript and html on the same page as well.
The simple solution: Generate your script to a .php file and include it as a script on the main page.