/    Sign up×
Community /Pin to ProfileBookmark

How to import a javascript into another javascript file?

I would like to have this code in a separate file called XMLHttpReq.js:

[code]function getXMLHTTPRequest()
XMLHttpRequest-objekt
{
var req = false;
try
{
req = new XMLHttpRequest();
}
catch(err1)
{
try
{
req = new ActiveXObject(“Msxml2.XMLHTTP”);
}
catch(err2)
{
try
{
req = new ActiveXObject(“Microsoft.XMLHTTP”);
}
catch(err3)
{
req = false;
}
}
}
return req;
}[/code]

Then, in my TestAjax.js I would like to get the XMLHttpRequest object by calling the method:

[code]var http = getXMLHTTPRequest();[/code]

But I guess I have to import the first file into my TestAjax.js to be able to call the getXMLHTTPRequest method. How do I import the file?

to post a comment
JavaScript

2 Comments(s)

Copy linkTweet thisAlerts:
@gisatApr 05.2010 — You can create a function :

[B]var Js_file=function(source_file){

var script=document.createElement("script");

script.setAttribute("type","text/javascript");

script.setAttribute("src",source_file);

document.body.appendChild(script);};[/B]


And in javascript you write: Js_file("TestAjax.js"); and your javascript code will added into your javascript code.

Or you can bind js file into your php(html) file:

into tag <head>

<script type="text/javascritp" src="TestAjax.js"></script>
Copy linkTweet thisAlerts:
@rnd_meApr 05.2010 — You can create a function :

[B]var Js_file=function(source_file){

var script=document.createElement("script");

script.setAttribute("type","text/javascript");

script.setAttribute("src",source_file);

document.body.appendChild(script);};[/B]


And in javascript you write: Js_file("TestAjax.js"); and your javascript code ...[/QUOTE]


note that that won't import the script, it merely request it to be added to the document. If you try to use the function before that external script is loaded, it will fail.

you can use document.write to add a script tag during page load, or you can use some kind of a monitor/agent that waits for the external file to be loaded before continuing.

let me know if you need any code for these ideas.
×

Success!

Help @Roxxor spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...