How can I make functions common between assets/js and static/js?

Viewed 45

I’m working on AMP project. I have an authorization callback that is defined in static/js (for some unknown reason, the callback should be defined in static/js). How I can make the function defined in assets/js to be visible in static/js?

My main js is included in HTML before that static/js and use this construction

{{ $js := resources.Get "js/custom.js" | js.Build }}
<script src="{{ $js.Permalink }}"></script>
2 Answers

If you define some functions in custom.js with a global scope, they should be visible in the static JS files.

MyObject = {
    function1: function(...) {...},
    function2: function(...) {...}
    // other functions...
}

And then, they can be called from the other file with:

MyObject.function1();

Now, it might be possible that the file is not ready to be called, or that from your custom JS file you need to have the other static JS file loaded first. In that case, you can "wait" until everything is fully loaded.

MyObject = {
    function1: function(...) {...},
    function2: function(...) {...}
    // other functions...
}

window.addEventListener('load', (event) => {
  // Page is fully loaded. 
  MyObject.function1();
});

If this doesn't work, we'd need to understand a bit better the code that's inside static to see how you could achieve this.

Related