Loading External JavaScript files

Suppose this is our external javascript file content.

(customscript.js)

It consist of a simple function

function SayHello()
{
    alert(‘Hello World’);

}


 

It is placed at the following path   ..\ISV\ExtJS. i.e. within ExtJS folder inside ISV.

Place the following code in the form load of an entity’s form.

var scriptElement=document.createElement("<script type=’text/javascript’>");

scriptElement.src="/isv/ExtJs/customscript.js";

document.getElementsByTagName("head")[0].insertAdjacentElement("beforeEnd",scriptElement);

SayHello();

At times, it would work properly however sometimes it would throw “Object expected” error. It is because browser load JavaScript files asynchronously. If the script isn’t loaded we would get the error.

So here we need to make use of onreadystatechange event.

So we would modify our script as following

 

var scriptElement=document.createElement("<script type=’text/javascript’>");

scriptElement.src="/isv/ExtJs/customscript.js";

scriptElement.attachEvent("onreadystatechange",loadScript);

document.getElementsByTagName("head")[0].insertAdjacentElement("beforeEnd",scriptElement);

function loadScript()

{

if(event.srcElement.readyState=="loaded" || event.srcElement.readState=="complete")

{

    SayHello();

}

}

 

 

Or we could also using XmlHttp request object to load the external file.

var url="/isv/ExtJs/customscript.js";

var xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");

xmlHttp.open("GET",url,false);

xmlHttp.send();

eval(xmlHttp.responseText);

SayHello();

 

Bye..


Author: Nishant Rana

I love working in and sharing everything about Microsoft.NET technology !

2 thoughts on “Loading External JavaScript files”

  1. I’m curious to find out what blog platform you’re utilizing?
    I’m experiencing some small security problems with my latest website and I’d like to find something more
    secure. Do you have any suggestions?

    Like

Share your thoughts

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s