Load External JavaScript Files


Lazy Loading JavaScript with KnackInitAsync()

If you lazyload JavaScript with event handlers, you will need to wrap any event handlers within the KnackInitAsync() function. This is a global function that Knack calls when it has completely loaded.

It also passes in the Knack jQuery object as the first parameter, $. Knack uses a sandboxed jQuery object to prevent conflicts with other jQuery versions you may be using.


Example: External JavaScript File with an Event Handler

// file.js
$(document).on('knack-scene-render.any', function(event, scene) {
  alert('Page rendered!');
});

Wrapping LazyLoad with KnackInitAsync()

Now let's load file.js into our Knack app using LazyLoad.js, wrapped in KnackInitAsync():

// Define `KnackInitAsync` globally
KnackInitAsync = function($, callback) {
  // REQUIRED: Expose Knack's jQuery globally
  window.$ = $;

  // Load external JavaScript
  LazyLoad.js(['https://example.com/javascript-files/file.js'], function () {
    console.log('Loaded external files!');

    // REQUIRED: Let Knack continue loading
    callback();
  });
};

Notes on KnackInitAsync()

  • This function can only be defined once.
  • If you are adding JavaScript directly in the Builder's custom code section, you do not need to wrap your handlers in this function — they are automatically called once Knack has loaded.