I am looking for a way to pass parameters into JavaScript from my website's backend, in this case ASP.NET MVC, but the problem is probably applicable to other languages.
I wish to use separate JavaScript files so that I can process/bundle/minify them, however the website is such that various parts are administrated via the backend. One perfect example is the displayed error message for a failed ajax call, being stored in the website backend in a translatable resource file so that it shows an error in which ever language the user has selected to view the site in.
For ordinary html markup, you can just use the razor syntax to inject the string into the markup generated, e.g.
<p>@Html.Localise("Generic.AjaxError.Message")</p>
If I keep the JavaScript in a script tag on the page then I can continue to use this method, however I will not benefit from JavaScript pre/post-processors that I would like to use (lint, babel, bundle, minify, etc.)
Two options I have thought of are to create a global window.localisedStrings
object (perhaps "injecting" this object into JavaScript IIFEs), although it may get slightly messy if I have separate objects for localisedStrings
, urls
etc. and there then becomes a hard dependency between the JavaScript file and a specific piece of code (the object's structure-building script) on the HTML page.
The other option is to add each of the values required as a data-
attribute on the <body>
tag. The JavaScript could then look for those values. As the "entry" JavaScript file is a page-specific file, it would be responsible for reading the values and passing them into the various methods that need to use them.
Is there a best-practice method of accomplishing what I need?