NeiL
NeiL

Reputation: 801

Load requirejs library only if it is not loaded on page

I am new in using requirejs(2.1.19). Currently i am developing an app using it. My problem what happens if some user already have requirejs(<2.1.19) on its page. It means two versions of requirejs is being loaded which will result a conflict. How to deal with this problem. So that my app overrrides the requirejs used by users.

I want that if user already have requirejs. It uses that js otherwise it uses requirejs which i serve Is there a way to do so ????

Upvotes: 0

Views: 129

Answers (1)

Mat&#237;as Fidemraizer
Mat&#237;as Fidemraizer

Reputation: 64923

You can check if some of global RequireJS functions are already defined. For example:

if(typeof define == "undefined") {
    // RequireJS isn't present...
}
// or...
if(typeof require == "undefined") {
    // RequireJS isn't present...
}

In order to conditionally load a library you'll need a standalone JavaScript loader. One of simplest file loaders is HeadJS.

if(typeof define == "undefined") {
     head.load("yourOwnRequire.js", function() {
         // RequireJS will be loaded asynchronously
     });
}

Note that loading libraries asynchronously has some implications. Some library may not be available once the document has been loaded, you need to think how to initialize your Web application carefully.

In the other hand, if you want to synchronously-load your RequireJS, take a look at this Q&A to check how to manually add a script tag using JavaScript:

Upvotes: 2

Related Questions