Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load one JavaScript file from another?

Tags:

javascript

How do you load one JavaScript file from another JavaScript file, like CSS? In CSS we use write @import url("mycss.css");.

Is there any way to do it in JavaScript?

like image 364
Vins Avatar asked May 05 '11 04:05

Vins


People also ask

Can I use a JavaScript function from another file?

As long as both are referenced by the web page, yes. You simply call the functions as if they are in the same JS file.


2 Answers

There's no @import-ish function/method in Javascript, but you can simply append a script to the <head> tag like so:

var newScript = document.createElement('script'); newScript.type = 'text/javascript'; newScript.src = '/path/to/js/file'; document.getElementsByTagName('head')[0].appendChild(newScript); 

Or like Edgar mentioned right before me you can use jQuery.

like image 159
musicinmyhead Avatar answered Sep 28 '22 23:09

musicinmyhead


Yes. If you want in pure JavaScript, you have to create dynamically a script tag, and append it to the document.

Yes. If you use the jQuery library, you can use the $.getScript method.

$.getScript("another_script.js"); 
like image 39
Edgar Villegas Alvarado Avatar answered Sep 28 '22 21:09

Edgar Villegas Alvarado