Let’s say that you have an external JavaScript Library that is used in some instances but not needed all the time so you wonder how you can load this file only when needed. Here is a short code snippet that will help you dynamically load JavaScript file using none other than
JavaScript itself.
The first time I needed this feature I fell into the trap of using the XMLHttpRequest object (AJAX route) with the evil eval() function; I don’t need to explain why this is not safe (hint: cross site scripting attack).
var developercaster = {
script: function (_src) {
var tag = document.createElement('script');
tag.setAttribute('type', 'text/javascript');
tag.setAttribute('src', _src);
document.getElementsByTagName('head')[0].appendChild(tag);
}
};
The breakdown
Create new “script” tag using document.createElement, set the “type” and “src” attributes, and finally append it to the “head” element (yes, it’s that simple).
Usage
Let’s create an external JavaScript file called “getLocation.js” and add the following function to it:
var getLocation = {
current:window.location.href
};
Now to load the “getLocation.js” file dynamically we would proceed as follows:
<script language="javascript" type="text/javascript">
window.onload = function () {
if (typeof getLocation == 'undefined') {
developercaster.script('getLocation.js');
}
alert(getLocation.current);
};
</script>
No comments:
Post a Comment