0

I want to add an external javascript file in another javascript file. For example my file name is info.js, now I want to include "https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js" in my info.js file. I don't want to use this CND <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> in my html file like this.

I did the following code, which adds the CDN to the html file, but it's not working.

function include(file) {
    var script = document.createElement('script');
    script.src = file;
     document.getElementsByTagName('script').item(0).before(script);
    }
    /* Include Many js files */
   include('https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js');

Actually I am not good at English. I hope you understand my problem. Have any solution for me?

Thanks

  • 1
    visit that address in your browser, `ctrl + a`, `ctrl + c` open your info.js file, `ctrl + v` ? – Dale Feb 24 '23 at 12:25
  • Can't you just add 2 separate ` – Justinas Feb 24 '23 at 12:26
  • just download that .js file into your own site's source tree alongside info.js and do ` – Alnitak Feb 24 '23 at 12:30

1 Answers1

1

Dynamically create a script element and set its src attribute to the axios library URL. Then it will append the script element to the head of the document. You can then use the axios library as usual in your info.js file.

// Create a script element
var script = document.createElement('script');
// Set the src attribute to the external library URL with a cache-busting parameter
script.src = 'https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js?' + Date.now();
// Append the script element to the head of the document
document.head.appendChild(script);
  • Its working only after reloading the page, its not work for first visitor. – Md Alamgir Hossain Feb 24 '23 at 14:14
  • You can add a cache-busting parameter to the script URL to solve the problem, like a timestamp or a random number. The code is edited (Added the time stamp to the script URL) try it :) – EL Amine Bechorfa Feb 24 '23 at 14:20
  • Uncaught (in promise) ReferenceError: axios is not defined http://localhost/new/pixel/index.js:48 promise callback* http://localhost/new/pixel/index.js:40 promise callback* http://localhost/new/pixel/index.js:33 – Md Alamgir Hossain Feb 24 '23 at 17:35