How to add Javascript to the footer of a TYPO3 Web Site
There will likely be times where you will add different features to your web site that require you to add some Javascript to the footer of your web site. This just means that you need to add the javascript to the bottom of the pages HTML just before the end </body> tag. Just today for example I had to add some code to the bottom of the page of this site that was required by Amazon Onelink. But it doesn't matter what service you are using, you can add any Javascript to the footer of your TYPO3 site really easily with some typoscript added to your template.
Here's an example from earlier today:
Today, I needed to add the following Javascript to the footer of my site:
<div id="amzn-assoc-ad-e9b8a32f-57ef-43c2-a908-314c39cce480"></div><script async src="//z-na.amazon-adsystem.com/widgets/onejs?MarketPlace=US&adInstanceId=e9b8a32f-57ef-43c2-a908-314c39cce480"></script>
So what I did was I created a file called AmazonOnelink.js and I pasted that above Javascript into it. I saved the file in my site package folder (but you can save javascript anywhere. Some people save javascripts in the fileadmin/ directory). I saved mine in the following directory location:
typo3conf/ext/site_package_typo3hub/Resources/Public/JavaScript/AmazonOnelink.js
So now that I have my javascript stored on my server where the TYPO3 installation can find it, I only have to add some typoscript to my setup section of my template to include the javascript in the site footer:
page.includeJSFooter { AmazonOnelink = EXT:site_package_typo3hub/Resources/Public/JavaScript/AmazonOnelink.js }
What you see above is all you need to do to have TYPO3 include that javascript. There's nothing else to do. You may have noticed that I prefixed the path name with EXT:. That's because it's located in a directory of my site package extension. I just recently learned about making site packages for sites and it makes it a lot easier to organize all of the files for a site.
But if I stored the AmazonOnelink.js file in the fileadmin folder, then I could just do the following typoscript and it would work just as well:
page.includeJSFooter { AmazonOnelink = EXT:site_package_typo3hub/Resources/Public/JavaScript/AmazonOnelink.js }
And do you see where I wrote AmazonOnelink to the left of the equals sign ("=") in each of the examples? I could have written anything there as long as it's a unique name for the Javascript that's being added.
All of the Javascripts you add in this way - and you can add many - will be put together into a single external file. But there are configuration options you can use if you don't want that to happen. You can read all about it in the docs.