In this article I will explain how to dynamically include an external JavaScript JS file in another external JavaScript JS file.
The external JavaScript JS file will be included using dynamic Script Tags.
 
Including an external JavaScript JS file in another external JavaScript JS file
In the following external JavaScript JS file I am loading jQuery external JS file dynamically using Script Tags.
In order to include any external JavaScript JS file, we need to append it to the HEAD section of the page and for that I am creating a dynamic script tag, setting its type, its source and then appending it to the HEAD element of the page.
Then to make sure whether jQuery is loaded, a check is performed inside the window onload event handler which sets the value of HTML SPAN if the jQuery is loaded successfully.
//Load jQuery
var script = document.createElement("SCRIPT");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", "http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js");
document.getElementsByTagName("head")[0].appendChild(script);
 
window.onload = function () {
    if (typeof (jQuery) != "undefined") {
        $("#lblStatus").html("jQuery loaded");
    }
}
 
 
HTML Markup
In the below HTML page, I have referenced the external JavaScript JS file which will internally load jQuery JS file.
There’s an HTML SPAN element which currently displays the message jQuery not loaded. Once the jQuery JS file is successfully loaded it will display the message jQuery loaded.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="Scripts/Scripts.js" type="text/javascript"></script>
</head>
<body>
    <span id="lblStatus">jQuery not loaded.</span>
</body>
</html>
 
 
Screenshot
Include a JavaScript JS file in another JavaScript JS file
 
Downloads