/    Sign up×
Community /Pin to ProfileBookmark

Possible to call function in external .js from internal function?

Is it possible to have a function in an external .js file, and then call this function from an internal script block? If it is, how do you do it? I have some validate-functions which can be used on several of my pages, and it would be more efficient to have them in external files, but I need to call those functions when I click the button.
I have tried searching, but the only results I get are how to make an external .js-file.

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@felgallSep 05.2005 — Make the external JS and link it into your page. You can then refer to everything in the external file as if it were coded at the place where the link appears.
Copy linkTweet thisAlerts:
@grantreidOct 04.2005 — Hi Stephan,

What if the js file is 3rd party and I have no means to modify it.

Effectively, I want to control when this script will be loaded (as it executes code immediately).

In some circumstances, I dont want the code to execute. So I need a way of dynamically 'including' the .js file.

Inside your html code you can do this,

<script type="text/javascript" scr="3rd_party_script.js"></script>

But, inside my html code, this script will always execute. How can I selectively do this from my own .js file?

Regards

Grant
Copy linkTweet thisAlerts:
@KorOct 04.2005 — 
So I need a way of dynamically 'including' the .js file.
[/quote]


use DOM methods to create it

ex:

in your page:
[code=php]
<script type="text/javascript">
function createEl(){
var oJs = document.createElement('script');
oJs.setAttribute('type','text/javascript');
oJs.setAttribute('src','myjs.js');
document.getElementsByTagName('head')[0].appendChild(oJs);
call();
}
</script>
[/code]


in myjs.js file, for instance:
[code=php]
function call(){
alert('blabla');
}
[/code]


Now when you fire the function createEl(), you will get the alert
×

Success!

Help @Khamul 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.6,
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,
)...