Inserting JavaScript in generated HTML
JavaScript code can be bundled in a custom plug-in and automatically inserted into the generated HTML pages to enable web analytics or dynamic content delivery.
About this task
This scenario walks through the process of creating a very simple plug-in
(com.example.html5-javascript
) that creates a new transformation type:
html5-javascript.
The html5-javascript transformation includes a custom page footer file with a JavaScript
tracking snippet and sets the args.ftr parameter to integrate the script content in the
HTML5 <footer>
element of the generated pages.
Note: This example inserts a tracking snippet for Google Analytics, but the basic approach is the same for other
analytics platforms or similar use cases that require custom JavaScript.
Procedure
Results
Tip: The files for this sample plug-in are included in the DITA-OT installation directory under
docsrc/samples/plugins/com.example.html5-javascript/ and on
GitHub.
The plug-in directory has the following layout and files:
com.example.html5-javascript
├── build_html5-javascript.xml
├── include
│ └── javascript.ftr.xml
└── plugin.xml
What to do next
- Run dita --install to install the plug-in and make the html5-javascript transformation available.
- Build output with the new transformation type to verify that the plug-in works as intended.
dita --input=my.ditamap --format=html5-javascript
- Open one of the generated HTML topic files in a modern web browser and check the JavaScript Console. When the page is loaded, Adding Google Analytics tracker will appear on the console to verify that the sample script is loaded.
- Remove the
console.log
debugging message from the sample JavaScript code, and replace the'UA-XXXXX-Y'
placeholder string with the tracking ID of the Google Analytics property you wish to track.
Tip: This example places the JavaScript code in the page footer to ensure that page display is not
delayed while the script is loaded. If your JavaScript code supports pre-loading and your application targets
modern browsers that recognize the
async
script attribute, you may prefer to insert the
JavaScript snippet in the <head>
element of the generated HTML files using the
args.hdf parameter instead.