I'm loading some JS via <script src="whatever.js" async></script> in the <head> section.…
- User
I'm loading some JS via
<script src="whatever.js" async></script>in the<head>section. That JS exports some object. NB: "exports" not in the sense of modules, but in a more global and generic sense. Anyways, I want to: 1) export that shit, and 2) scope it. I have full control over both the page, and the loaded library. What are my options? Assistant
You have several solid options for exporting and scoping that JavaScript object:
Option 1: Namespace on window In your loaded JS file:
window.MyLibrary = { // your exported stuff };Then access it anywhere as
window.MyLibraryor justMyLibrary.Option 2: Custom global namespace Create a scoped container:
// In your main page or the loaded JS window.MyApp = window.MyApp || {}; window.MyApp.SomeLibrary = { // your exported stuff };Option 3: IIFE with controlled exposure In your loaded JS:
(function() { // private scope var privateStuff = {}; // expose only what you want window.MyLibrary = { publicMethod: function() { /* ... */ }, publicProp: 'value' }; })();Option 4: Promise-based loading with scoping In your main page:
window.libraryReady = new Promise(resolve => { window.resolveLibrary = resolve; }); // In your loaded JS window.resolveLibrary({ // your exported object }); // Usage libraryReady.then(lib => { // use lib here });Option 5: Event-based approach Loaded JS dispatches a custom event with the object, main page listens and stores it in whatever scope you want.
Which direction appeals to you most? The namespace approach is probably the simplest if you just want clean global access.
- User
Let's see... So, any option that includes installing node is right out the window. Like, no discussion here. Then, IIFE I already have. Entire loaded script is wrapped in an IIFE, but it needs to export something. So yeah, I can write to the global namespace (e.g.
window), but then the caller does not control the scope. You get what I mean? It is possible, that the name chosen by the library clashes with the loading code (yeah, I control both, but I can make a mistake). I can fire a global event, which carries the object I wish to expose. But.. it's the same problem. Only now the clash is not insidewindow's property, but in the event id namespace. Modules have too many requirements. I want to be able to copy-paste this thing, and it should Just Work (tm). Assistant
Ah, I see what you're getting at - you want the caller to control the scope/naming, not the library itself. Here are some cleaner approaches:
Option 1: Callback-based export In your main page, before loading the script:
window.__libraryCallback = function(exportedObject) { // caller controls where it goes const myLib = exportedObject; // or window.myChosenName = exportedObject; // or someNamespace.whatever = exportedObject; };In your loaded JS:
(function() { // your library code const myExports = { /* stuff */ }; if (window.__libraryCallback) { window.__libraryCallback(myExports); delete window.__libraryCallback; // clean up } })();Option 2: Promise resolver pattern Main page:
let resolveLib; window.__libPromise = new Promise(r => resolveLib = r); window.__libResolver = resolveLib;Loaded JS:
(function() { const exports = { /* your stuff */ }; if (window.__libResolver) { window.__libResolver(exports); delete window.__libResolver; delete window.__libPromise; } })();Usage:
window.__libPromise.then(lib => { const myLib = lib; // you control the name });Option 3: Stack-based approach Main page sets up a "delivery box", library drops stuff in it:
window.__libDelivery = []; // load script const myLib = window.__libDelivery.pop();The callback approach is probably cleanest - you set up exactly how you want to receive the export before loading.
- User
but how can i pass additional data via that
<script>tag? Assistant
You can't pass data directly through the
<script>tag itself, but you have several ways to get data to your loaded script:Option 1: Data attributes + query the DOM
<script src="whatever.js" async data-config='{"name":"myLib","version":"1.0"}'></script>In your loaded JS:
(function() { const scriptTag = document.querySelector('script[src*="whatever.js"]'); const config = JSON.parse(scriptTag.dataset.config); const exports = { /* your stuff */ }; window[config.name] = exports; // or use config however })();Option 2: Global config object Set up config before loading:
window.__libConfig = { exportName: 'myChosenName', someOtherOption: 'value' };<script src="whatever.js" async></script>Option 3: URL parameters
<script src="whatever.js?exportName=myLib&option=value" async></script>In loaded JS:
(function() { const scriptSrc = document.currentScript?.src || document.querySelector('script[src*="whatever.js"]').src; const url = new URL(scriptSrc); const exportName = url.searchParams.get('exportName'); window[exportName] = { /* your exports */ }; })();Option 4: Combine with callback approach
window.__libConfig = { exportName: 'myLib' }; window.__libraryCallback = function(exports) { window[window.__libConfig.exportName] = exports; };The URL params approach is pretty clean since everything's in one place in your HTML.
- User
yes!
currentScriptit is! nice one Assistant
Nice choice!
document.currentScriptis really elegant for this - the script can introspect its own loading context.Just a heads up: since you're using
async,document.currentScriptmight benullby the time your script runs (because it's no longer the "currently executing" script). The fallback withquerySelectorhandles that case.If you want to be extra safe, you could also grab the script reference immediately:
(function() { const thisScript = document.currentScript || document.querySelector('script[src*="whatever.js"]'); // rest of your code can use thisScript })();But yeah, URL params +
currentScriptgives you a really clean, self-contained way to pass config data. No global namespace pollution, everything's right there in the HTML tag.