Reputation: 2901
I have a few snippets of javascript scattered about my pages - many are contained in my own .js files, however some of the stuff that I've found online sits directly on the page.
I'm not too familiar with how javascript interacts with a page - is there a difference between adding the script inline or adding a reference to the external file?
Upvotes: 19
Views: 37762
Reputation: 19
Consider this. If you're working in php; WordPress for example. You may need data from some wp functions like pagination, current category, etc and an inline script may be appropriate.
You can do something like:
<script>
var currentPageNumber = <?php echo get_query_var('paged'); ?>
</script>
If using a separate js file you'll need to localize a script with all of the backend data (similar to an inline script) then call the variables within your external file
Upvotes: 0
Reputation: 309
External script files
External files decrease page rendering speed as the browser has to stop parsing and download the external file. This adds a network round trip which will slow everything down. Also because external files are cached it makes it tough to delete them if the have been updated
Inline code
Although inline code is much harder to read and analyse as it just looks like a lump of code chucked together. It is hard work having to find the problem when debugging, making life as a programmer tough
Hope this helps you understand a bit more :)
Upvotes: 9
Reputation: 3685
There is little difference in using one or the other way. The real difference comes from the advantages/disadvantages that each one has.
Inline scripts
External scripts
Upvotes: 26
Reputation: 1871
Generally there is no difference as indicated in the comments. But, if the snippet is embedded in the middle of the HTML in the page and it is not a function, it is executed immediately. Such script segments may have a difference in behavior when moved to a separate JS file when enough care is not taken.
Upvotes: 2
Reputation: 23850
Looking at the <script>
tag documentation, you can see that you can use the async
and defer
attributes only with external scripts, which might have an effect on scripts that do not use event listeners as entry points.
Other than that, inlining renders a browser unable to cache it on its own, so if you use the same script on different pages, the browser cache cannot kick in. So it might have an effect on performance and/or bandwidth usage.
And, of course, splitting code up into files is one way of organizing it.
Upvotes: 2