Topic on Project:Support desk

Dynamically generating JavaScript but using ResourceLoader?

3
Richcoups (talkcontribs)

Is there a way to dynamically generate the JavaScript that's to be loaded for a page (e.g. the script uses the current page's title) yet use ResourceLoader? Right now I'm using:

$output = RequestContext::getMain()->getOutput();

$output->addModules('ext.JSRun');

and ext.JSRun is defined in extension.json ResourceModules to be a "script.js" in the extension directory. Problem is, it's going to load the same script every time without a way to customize it using PHP for every page.

I could use the makeInlineScript function in ResourceLoader, but inline scripts aren't recommended. Is there a better way to approach the problem?

Ciencia Al Poder (talkcontribs)

Use a hook and add the necessary logic to call $output->addModules('ext.JSRun'); only when needed

101.160.147.64 (talkcontribs)

If you want a totally dynamic script, it has to be inline. Even if you weren't using RL, browsers would still cache the script file, preventing you from changing the script, unless you are constantly breaking the cache. If your script doesn't need to change on every request, and doesn't have any user-specific code, then just modifying the file should get RL to break the cache. Otherwise, consider changing the script to be static, while making use of external dynamic data, which you could then include on the page in some form such as a JSON blob, or as part of the site options.