Site icon Sibeesh Passion

Dynamically load & check whether it is loaded or not

Introduction

Since we are all working with client-side programming technologies, we may need to load JavaScript files dynamically sometimes. So we will learn how to do that in this article.

Using the code

First of all we will just create two buttons for testing as follows.

[html]
<input type=“button” id=“loadjs” value=“Load Js” onclick=“load()” />
<input type=“button” id=“chk” value=“Check Load Js” onclick=“checkLoad()” />
[/html]

Once that is added, now it is the time to load the script.

Please note that you must include that script file to your solution. Here I am adding the jquery-1.7.2.min.js.

Now call the load function.

Load function

[js]
function load() {
var dynaScript = document.createElement(“script”);
dynaScript.id = “dynaJS”;
dynaScript.language = “javascript”;
dynaScript.type = “text/javascript”;
dynaScript.src = “jquery-1.7.2.min.js”;
document.getElementById(“myHead”).appendChild(dynaScript);
}
[/js]

Now we can check whether it is loaded or not.

checkLoad() function

[js]
function checkLoad() {
if (!window.jQuery)
alert(“Not loaded”);
else
alert(“Loaded”);
}
[/js]

Complete Code
[html]
<!DOCTYPE html>
<html xmlns=“http://www.w3.org/1999/xhtml”>
<head id=“myHead”>
<title>Load JS Files with script tag</title>
<script>
function load() {
// script creation start
var dynaScript = document.createElement(“script”);
dynaScript.id = “dynaJS”;
dynaScript.language = “javascript”;
dynaScript.type = “text/javascript”;
dynaScript.src = “jquery-1.7.2.min.js”;
// script creation end
document.getElementById(“myHead”).appendChild(dynaScript);
//Finally add it to our head element here.
}
function checkLoad() {
if (!window.jQuery)
alert(“Not loaded”);
else
alert(“Loaded”);
}
</script>
</head>
<body>
Sibeesh Passion (www.sibeeshpassion.com)
<input type=“button” id=“loadjs” value=“Load Js” onclick=“load()” />
<input type=“button” id=“chk” value=“Check Load Js” onclick=“checkLoad()” />
</body>
</html>
[/html]

Output

Now we will run the application and see the output. I have included the output as in the images below.


 Figure: Browser console before loads JavaScript


Figure: After loads JavaScript

When you click the Check Load button, you will get an alert saying that jQuery has been loaded.

Conclusion

Please provide your valuable suggestions and comments. Thanks in advance.

Kindest Regards,
Sibeesh Venu

Exit mobile version