We can include one js file in another js by the following ways:-
jQuery.getScript( url [, success ])
This function basically loads a javascript file using a GET HTTP request from the server and then execute it. <./p>
Here is an example code-
$.getScript(eg-script.js", function(){
alert("Script loaded");
});
This callback is fired once the script has been loaded. But it doesnt mean that it is necessarily executed.
Dynamic script loading
This is the ideal way to do this by adding a script tag which has a script URL in the HTML.
Here is an example code-
<script>
var egHead = document.getElementsByTagName('HEAD').item(0);
var egScript= document.createElement("script");
egScript.type = "text/javascript";
egScript.src=eg-1.js";
egHead.appendChild( egScript);
</script>
We can also use XMLHTTP for this purpose.
Get javascript using XMLHTTP,then create script object
For an example you can refer to the following link:
http://ntt.cc/2008/02/10/4-ways-to-dynamically-load-external-javascriptwith-source.html
Using this we face some cross-domain issues. Therefore, the preferred way of injecting js code is using ajax and then eval() the code.
0 Comment(s)