How to rearrange javascript function execution order independent of include order.
A question that assists, but doesn't completely answer my question: Can you have multiple $(document).ready(function() sections? (The answer is yes, and they execute in the order that they are added to jQuery.ready()).
I am trying to make my javascript logged-in/not logged-in aware, for convenient notification purposes, on my BBG ninjawars.net. I was hoping to use a simple system of having the server-side php write out a javascript function call setLoggedIn()
when a page is logged in, and write out a call to clearLoggedIn()
when a page is being viewed while logged out:
<head>
...
<!-- All the global ninjawars javascript, defines the setLoggedIn(), clearLoggedIn(), and modifyPageLayout() functions and (currently) calls modifyPageLayout() within jQuery.ready() -->
<script type="text/javascript" src="js/nw.js"></script>
{if $logged_in} // Server-side check.
<script type="text/javascript">
<!--
setLoggedIn();
// -->
</script>
{else} // Server-side check found that the user was not logged in.
<script type="text/javascript">
<!--
clearLoggedIn();
// -->
</script>
{/if}
</head>
Problems:
Currently, the order is: - define setLoggedIn() and clearLoggedIn() globally (in nw.js) - Add page/information modification code, lets call it modifyPageLayout() that needs to be informed of logged-in/logged-out to jQuery.ready() (in nw.js) - Call setLoggedIn() or clearLoggedIn() inline in script tags on the page.
I don't know how to make sure that the calls to setLoggedIn() or clearLoggedIn() occur before modifyPageLayout(), which is currently wrapped in a jQuery.ready() block, and would thus run whenever the DOM loaded.
If I added setLoggedIn() and clearLoggedIn() to jQuery.ready() blocks, they would be executed in the order added, thus the order would become:
modifyPageLayout()
, thensetLoggedIn()
orsetLoggedOut()
so all in jQuery.ready() blocks doesn't accomplish the intent.setLoggedIn() and clearLoggedIn() currently rely on code defined nw.js, so I can't call them before including nw.js.
One potential solution:
I could delay the modifyPageLayout function by writing it as:
modifyFunction = modifyPageLayout; // Non-executed first-class function variable. (created in nw.js)
setLoggedIn(); // inline in the head of the page
modifyFunction(); // inline in the head of the page
Anyone have other solutions?