Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Include" one javascript file to another one [duplicate]

Tags:

javascript

I have 2 separate javascript files

#1.js
String.prototype.format = ....
String.prototype.capitalize = ....

#2.js

//................
var text = "some text{0}".format(var1)
//................

How do I make string#format and string#capitalize available in the second file?

like image 384
Alan Coromano Avatar asked Feb 28 '13 12:02

Alan Coromano


People also ask

Can you include one JavaScript file in another?

We can include a JavaScript file in another JavaScript file using the native ES6 module system. This allows us to share code between different JavaScript files and achieve modularity in the code. There are other ways to include a JS file like Node JS require, jQuery's getScript function, and Fetch Loading.

How do I copy a variable from one JavaScript file to another?

To import a variable from another file in JavaScript:Export the variable from file A , e.g. export const str = 'Hello world' . Import the variable in file B as import { str } from './another-file.

Can you have multiple JavaScript sources?

It is not possible to load multiple javascript files in a single <script> element. You have to have to have an individual <script> element for each script you are referencing..


1 Answers

JavaScript executes globally. Adding both scripts on the page makes them available to each other as if they were in one file.

<script src="1.js"></script> <script src="2.js"></script> 

However, you should note that JavaScript is parsed "linearly" and thus, "first parsed, first served". If the first script needs something in the second script, but the second script hasn't been parsed yet, it will result in an error.

If that happens, you should rethink your script structure.

like image 66
Joseph Avatar answered Sep 28 '22 04:09

Joseph