It seems like very common practice to load scripts at the end of a page now / not in the <head>
. The problem is when you need to run some jQuery inline in the body due to template structure, variable access, etc., depending on project.
What is the easiest way (preferably vanilla JS) to queue a function to run after jQuery becomes defined later?
There are lots of complicated JS libraries for handling this and I'd prefer a brain dead / understandable process with zero documentation.
Is there an accepted "one liner" that's useful without loads of code?
Here's round 1 with CoffeeScript that works, just to show I'm putting some effort into answering it myself. Next up I will convert this to JS and try to come up with a simpler api.
class root.DeferUntil
constructor: ({@deferredFunction, @deferralCheck} = {}) ->
@interval = setInterval @executeIfLoaded, 500
executeIfLoaded: =>
if not @executed and @deferralCheck()
@deferredFunction()
clearInterval @interval
new DeferUntil
deferredFunction: ->
console.log "Hi, #{$} shouldn't raise errors"
deferralCheck: ->
$ != undefined