1

I need to get a params passed to JS file by an external service (I can't edit loading logic) or URL of JS script file.

For example, my script is loading by URL: /widgets/<code>/<version>/script.js?v=<version> (version are the same)

The biggest problem associated with the fact that a lot of such scripts can appear on the page (Up to 100-150 pieces). Accordingly, you need to get the URL or parameters of the script that is currently connected

The second big problem is that scripts are loaded without using the script tag. (The service uses RequireJS).

Therefore, this answer, for example, is not relevant. How can I get URL of JS file in same JS file?

At the output, you need to get <version>

Jatniel
  • 1,967
  • 2
  • 19
  • 27
Mr. Leo
  • 11
  • 4

1 Answers1

2

If you are using requirejs as loader you can do as follows

  1. Implement a setVersion(version) function in each of the modules you need to load

  2. Use the callback of requirejs to call that setVersion()

    requirejs(["foo/2.0/script.js"], foo => {
      //this is called after the module foo is loaded
      foo.setVersion("2.0");
    })
    

If you cannot modify the loading logic at all (ie adapt the callback) you are pretty much out of luck. Then there is no way of getting anything from the url from within the script. Because at the moment your script is loaded and evaluated by requirejs it's just an ordinary string which doesn't know where it came from ...

derpirscher
  • 14,418
  • 3
  • 18
  • 35
  • 1
    It's not possible at all, unfortunately. We work with a clumsy vendor who is not ready to make changes. Or ready, but very slowly – Mr. Leo Mar 07 '23 at 09:18
  • 1
    Just to point out the obvious: Can't you just add some `const version = "2.0"` to a `script.js`? Or inject something at the backend from where `script.js` is loaded. But of course both these ideas might just result from a misunderstanding of your project's structure ... – derpirscher Mar 07 '23 at 09:20
  • We are running the script within a system with a very tight cache. version is needed in order to load other files of the same version. The problem is that the files are often updated by hand and constantly fixing the version by hand is a road to nowhere. Accordingly, in an ideal world, take the version from the path and load other resources using it. But according to your answer, this is not possible. It is also impossible to modify the script with a back. It is loaded into vendor files and is not modifiable. Only front, only hardcore... ( – Mr. Leo Mar 07 '23 at 09:58
  • 1
    "The problem is that the files are often updated by hand" — This sounds like a job for version console (e.g. git) and a build toolchain that stamps the version from Git into the files automatically. – Quentin Mar 07 '23 at 13:23