Load External JavaScript Files

  • Embedded Knack app: Include any external scripts by loading them with of the page)
  • Inside a Knack app: Use LazyLoad from within the Knack custom Javascript:
// The first parameter is an array of files to load.
// The second parameter is a function to execute after all the libraries have completed loading.
LazyLoad.js(['https://cdnjs.cloudflare.com/ajax/libs/datejs/1.0/date.min.js'], function () {
    alert('All my files have completed loading!');

// load some external CSS files
var css_files = ['https://cdnjs.cloudflare.com/ajax/libs/1140/2.0/1140.css', 'https://cdnjs.cloudflare.com/ajax/libs/SlickNav/1.0.3/slicknav.min.css'];
LazyLoad.css(css_files, function () {
    alert('All my CSS files have completed loading!');

Loading JS Files with Event Handlers from Outside of the Builder

If you lazyload JavaScript with event handlers, you will need to wrap any event handlers within the KnackInitAysnc() function. This is a global function which 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 in order to prevent conflicts with other jQuery versions you may be using.

Let's take a look at an example where our external JavaScript file includes an event handler:

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

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

// In the Builder
KnackInitAsync = function ($, callback) {
  // REQUIRED: Explicitly include jQuery
  window.$ = $;
  // Load the file from wherever it is hosted
  LazyLoad.js(['https://example.com/javascript-files/file.js'], function () {
    console.log('Loaded external files!');
    // REQUIRED: Tell the Knack app to go ahead and finish loading

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.