Search code examples
javascriptbookmarklet

How to not expose a 3rd party library on the global scope?


I am writing a bookmarklet that uses another 3rd party library in order to perform some of its functions. How could I make use of the 3rd party library in the bookmarklet without exposing the library on the global scope?

Source Code is currently being committed in - https://github.com/shanti2530/bookmarklets The library in question is moment.js which currently is being exposed on the global scope if the user uses the bookmarklet.


Solution

  • Since you're just including the moment.js code in your own bookmarklet, you can just put the moment.js code inside your outer function. That will make it available to you to use.

    To make no global variables, you will have to edit the moment.js source because it explicitly creates global symbols regardless of how it is included. I haven't studied its source extensively, but it looks like the function makeGlobal() is where it defines its interface. You could modify that to add the moment function as a method on an object you declare in your function f() so you don't affect the global scope.

    It looks like you would modify this line:

    // makes moment function globally available
    this['moment'] = moment;
    

    to change how the moment() function is accessible.