I'm working in my .js file. When my function, mainPaginationClicked is called, I want it to also execute another function, rotateMessage. rotateMessage is declared in the script tags of my html document. Is there a way to call this function from my .js file?
-
as long as it is declared and global, you can call it anywhere, you have to show an example though – Ibu Oct 24 '12 at 17:35
-
Why not put `rotateMessage` in your `.js`? Seems strange to have an external javascript dependent on inline functions – Mike Park Oct 24 '12 at 17:38
-
I ended up just putting the function in the .js. I came to the same conclusion: it didn't make sense putting it into a html script tag – Sean Smyth Oct 24 '12 at 20:32
-
Slightly off topic but often it does make sense to have external js dependent on inline. If you're creating a system where JavaScript is dependent on information that is most easily provided from the back end, then outputting inline js using the server side language but keeping most of the js in files that are static is a simple solution (normally preferring something like declarative configuration, but a dependency nonetheless) – Matt Whipple Oct 24 '12 at 21:34
-
@MattWhipple Wouldn't you agree that a better solution is to use a script tag that points to a servers side resource (script or otherwise) that returns the appropriate js? – Asad Saeeduddin Oct 24 '12 at 22:12
-
@Asad, entirely depends on the situation. That may introduce an unjustifiable amount of complexity, and if its a configuration setting that is limited in scope and therefore not likely to be reused then you're introducing an additional request (potentially a blocking one) which would hurt front end performance. From an organizational standpoint there should be more concern over keeping the source clean rather than the output. This type of purism can lead to over-engineered approaches with no practical benefit, and most projects have other pieces that need far more attention. – Matt Whipple Oct 25 '12 at 01:56
3 Answers
Yes, you can call this as it would be in your .js file. Functions in JS are shared between files, as variables are, too.

- 8,200
- 5
- 33
- 46
So long as you load the JavaScript file after the function is delcared in the HTML (or only invoke the function after it is declared), then the function you declare will be available within the same JavaScript context. The actual file location doesn't matter, only the in-memory namespaces.
The default behavior in a browser is to block while loading JavaScript using script
tags, so you can safely write the JavaScript resources in the order that you want them executed without worrying about the fact that the external file needs to be loaded (and unless explicitly controlled otherwise they all get pooled together in a global namespace).

- 7,034
- 1
- 23
- 34
Provided you make sure your js file is included after the script tag, there should be no problems with invoking rotateMessage

- 46,193
- 6
- 90
- 139