简体   繁体   中英

Include a JS file in another JS file with pure JS

I want to include a JS file in another JS file in pure JS, so without NPM or Yarn.

I do not use classes/modules, so how can I do this?

What I mean with Pure JS

Pure JS is JavaScript that you directly can include in your HTML, like so:

<script src="path/to/pure-js-file.js"></script>

What I tried

Here are my two files:

app.js

require('./components/navbar.js');

components/navbar.js

alert('Navbar component!');

But I get this error:

Uncaught ReferenceError: require is not defined

Because normal browsers don't know the require keyword.

Since you don't want to use modules you could load an additional script with an AJAX call and then use eval to run it. This is the most straightforward way, but it is limited to your domain because of the JavaScript sandbox security model. Using eval also opens the door to bugs, hacks, and security issues. you can do it like so:

function getFile(filePath) {
    var httpRequest = new XMLHttpRequest();

    if (!httpRequest) {
      alert('Cannot create an XMLHTTP instance');
      return false;
    }

    httpRequest.onreadystatechange = function() {
      if (httpRequest.readyState === XMLHttpRequest.DONE) {
        if (httpRequest.status === 200) {
          eval(httpRequest.responseText);
        } else {
          alert('There was a problem with the request.');
        }
      }
    };

    httpRequest.open('GET', filePath);
    httpRequest.send();
}

getFile('./components/navbar.js');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM