How to prevent loading a Javascript library more than once

1

Hello, I have a question regarding loading a Javascript library. I'm building an application that builds components with the reusability, and for that the structure of each component would be created like this:

//componente foo
.foo = {
    style : "foo.css",
    template : "foo.html",
    script : "script.js",
    "imgDir" : "img",
    //etc...
};

Thinking of a logic to facilitate the maintenance and reuse of these components, and also in the class system of a strongly typed application I have the interest to include all dependencies of the scripts of this component in the same component, so if such a script was not loaded before, it should be for only then the system to run.

I took this idea to prevent loading the same library from require_once of PHP. Is there any way to, I force the DOM to see if the script already exists on the page so it does not occur from the same duplicate link from it? It occurred to me in another moment and it ended up that the new insertion of Jquery kinda stopped my application because it was recreating the contents of a library inside the document and with that I lost instances and methods already declared and in use. p>     

asked by anonymous 19.10.2016 / 21:26

2 answers

2

You could create a variable for each library that you load ... Then when it loads, see if it already exists. If it does not exist, charge. Tb can increase the stop level:

link

  

I would suggest that you use either require.js or head. js for this kind of thing. They are fully-featured and provide performance benefits as well.

    
19.10.2016 / 22:37
0

First of all, as my comment says, you do not lose an instance of a class if it is redefined in an identifier or property, for example:

class A {
    method() {}
}

let instance = new A
A = null

instance.method // Function
instance.constructor // A

I hope you finally understand my comment.

Returning to the subject:

  

Is there any way I can force the DOM to see if the script already exists on the page so that it does not duplicate the link?

And why would this happen? Anyway, you can not prevent this duplication through HTML, you would need one of the languages that have access to the DOM and are supported by browsers, often JavaScript, and VBScript can also be used in

21.10.2016 / 13:42