Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get script URL with RequireJS?

When simply loading your script with a <script /> tag, you can retrieve the script URL like this:

var scriptURL = Array.prototype.pop.call (       // get the last...
        document.getElementsByTagName ('script') // ...script tag on the page...
    ).src.split ('?') [0];                       // ...take 'src' attribute...
                                                 // ...and strip the query string

This is a bit of a hack, but can be very useful sometimes, for a number of reasons (e.g., when there are other resource files script relies on and you don't want to hardcode the path). It works because at the time of execution the last <script /> tag existing on the page is your script.

I'm not sure if that is so when loading scripts with RequireJS. Is there a similar way in RequireJS to retrieve the script URL from inside the module definition?

like image 408
Septagram Avatar asked Dec 26 '22 22:12

Septagram


1 Answers

You can require the module module, which commonly used to pass the special config settings:

define(['module'], function (module) {
  console.log(module)
}

This will give you an object holding the id and the uri to the module

like image 187
Andreas Köberle Avatar answered Dec 28 '22 11:12

Andreas Köberle