JavaScript - requires the function of loading external JS files

I recently added facebook to my website as a button, the twitter for us and the Google +1 button. I want their JS scripts to load when I tell them to load.

Therefore, I need a function that loads external JS files. I do not need to know when the file has finished downloading (no callback needed).

I found some methods / functions on the Internet, but I want to know which one is best for this situation?

4 ways to dynamically load external JavaScript
Dynamic loading of JS libraries and detection when loading them
Best way to load external JavaScript

Thanks.

Edit : Added methods / functions that I found.

+4
source share
4 answers

This may be useful:

  function loadScript (url, callback) {

     var script = document.createElement ("script")
     script.type = "text / javascript";

     if (script.readyState) {// IE
         script.onreadystatechange = function () {
             if (script.readyState == "loaded" ||
                     script.readyState == "complete") {
                 script.onreadystatechange = null;
                 callback ();
             }
         };
     } else {// Others
         script.onload = function () {
             callback ();
         };
     }

     script.src = url;
     document.getElementsByTagName ("head") [0] .appendChild (script);
 }
+4
source

I would recommend using jQuery getScript (). For the twitter button, you upload the appropriate script as follows:

$.getScript("//platform.twitter.com/widgets.js") 

Of course you need to load jquery into your script, and don't forget to add the necessary for the twitter button in your html.

+5
source

Sort of

 function getScript(url) { e = document.createElement('script'); e.src = url; document.body.appendChild(e); } getScript('jstoload.js'); 

+1
source

YUI Loader is a good choice for you. It will also allow you to add your own modules so that you can download them on demand, as well as download all the other JS files that are also needed.

0
source

Source: https://habr.com/ru/post/1383183/


All Articles