How do I include a JavaScript file in another JavaScript file? -
is there in javascript similar @import
in css allows include javascript file inside javascript file?
the old versions of javascript had no import, include, or require, many different approaches problem have been developed.
but recent versions of javascript have standards es6 modules import modules, although not supported yet browsers. many people using modules browser applications use build and/or transpilation tools make practical use new syntax features modules.
es6 modules
note currently, browser support es6 modules not particularly great, on it's way. according this stackoverflow answer, supported (but behind flags) in chrome 60, firefox 54 , ms edge 15, safari 10.1 providing support without flags.
thus, still need use build and/or transpilation tools valid javascript run in without requirement user use browser versions or enable flags.
once es6 modules commonplace, here how go using them:
// module.js export function hello() { return "hello"; } // main.js import {hello} 'module'; // or './module' let val = hello(); // val "hello";
node.js require
node.js using module.exports/require system. can use babel
transpile if want import
syntax.
// mymodule.js module.exports = { hello: function() { return "hello"; } } // server.js const mymodule = require('./mymodule'); let val = mymodule.hello(); // val "hello"
there other ways javascript include external javascript contents in browsers not require preprocessing.
ajax loading
you load additional script ajax call , use eval
run it. straightforward way, limited domain because of javascript sandbox security model. using eval
opens door bugs, hacks , security issues.
jquery loading
the jquery library provides loading functionality in 1 line:
$.getscript("my_lovely_script.js", function() { alert("script loaded not executed."); });
dynamic script loading
you add script tag script url html. avoid overhead of jquery, ideal solution.
the script can reside on different server. furthermore, browser evaluates code. <script>
tag can injected either web page <head>
, or inserted before closing </body>
tag.
here example of how work:
function dynamicallyloadscript(url) { var script = document.createelement("script"); // make script dom node script.src = url; // set it's src provided url document.head.appendchild(script); // add end of head section of page (could change 'head' 'body' add end of body section instead) }
this function add new <script>
tag end of head section of page, src
attribute set url given function first parameter.
both of these solutions discussed , illustrated in javascript madness: dynamic script loading.
detecting when script has been executed
now, there big issue must know about. doing implies you remotely load code. modern web browsers load file , keep executing current script because load asynchronously improve performance. (this applies both jquery method , manual dynamic script loading method.)
it means if use these tricks directly, you won't able use newly loaded code next line after asked loaded, because still loading.
for example: my_lovely_script.js
contains mysuperobject
:
var js = document.createelement("script"); js.type = "text/javascript"; js.src = jsfilepath; document.body.appendchild(js); var s = new mysuperobject(); error : mysuperobject undefined
then reload page hitting f5. , works! confusing...
so ?
well, can use hack author suggests in link gave you. in summary, people in hurry, uses event run callback function when script loaded. can put code using remote library in callback function. example:
function loadscript(url, callback) { // adding script tag head suggested before var head = document.getelementsbytagname('head')[0]; var script = document.createelement('script'); script.type = 'text/javascript'; script.src = url; // bind event callback function. // there several events cross browser compatibility. script.onreadystatechange = callback; script.onload = callback; // fire loading head.appendchild(script); }
then write code want use after script loaded in lambda function:
var myprettycode = function() { // here, whatever want };
then run that:
loadscript("my_lovely_script.js", myprettycode);
note script may execute after dom has loaded, or before, depending on browser , whether included line script.async = false;
. there's great article on javascript loading in general discusses this.
source code merge/preprocessing
as mentioned @ top of answer, many developers use build/transpilation tool(s) webpack, babel, or gulp in projects, allowing them use new syntax , support modules better, combine files, minify, etc.
Comments
Post a Comment