This waits for a thirdparty library to finish loading, then executes a JavaScript function with turnOn and passes a domAttribute as parameter. The executed JavaScript then triggers thirdparty library code, which modifies the DOM element in the page that causes an animation.
In this tutorial you'll learn how to:
- Include an external library
- Execute a JavaScript function after the library has finished loading
-
-
@inherits Custom.Hybrid.Razor14
@{
// Create unique DOM attribute with Module Id
var domAttribute = "turn-on-require-many-" + CmsContext.Module.Id;
var data = new {
domAttribute
};
}
@* Inject attribute into DIV, to make it accessible for query *@
<div @domAttribute></div>
@*
Wait for thirdparty library "spritejs" to load,
then execute the window.turnOnTutorial200.init function
and pass the domAttribute as JSON
*@
@Kit.Page.TurnOn("window.turnOnTutorial200.init()", data: data, require: "window.spritejs")
@* Include thirdparty library from CDN *@
<script src="https://unpkg.com/spritejs@3/dist/spritejs.js"></script>
@* Include local JavaScript file *@
<script src="@App.Path/tutorials/turnon-use/js/200-multi-file.js" @Kit.Page.AssetAttributes()></script>
Source Code of 200-multi-file.js
// Use an IFFE to ensure the variables are not exposed globaly
// See https://developer.mozilla.org/en-US/docs/Glossary/IIFE
(() => {
// Data gets passed as a single object, so we need to deconstruct it.
function init({domAttribute}) {
// The element gets found in the DOM by a querySelector with the passed attribute
const foundElement = document.querySelector(`[${domAttribute}]`)
foundElement.style.width = '100%';
foundElement.style.height = '250px';
// Thirdparty code gets executed
animateSpaceship(foundElement)
}
const tt = window.turnOnTutorial200 = window.turnOnTutorial200 || {};
tt.init = tt.init || init;
// Example code that consumes thirdparty library
function animateSpaceship(container) {
const {Scene, Sprite} = spritejs;
const scene = new Scene({container, width: 1000, height: 250, mode: 'stickyTop'});
const layer = scene.layer();
const spaceShip = new Sprite('https://images.squarespace-cdn.com/content/v1/528a31e5e4b00863f1646510/1562710379584-IOMK7TTBLH7H8GJ8QB1A/Screen+Shot+2019-07-09+at+5.12.37+PM.png');
spaceShip.attr({
anchor: [0, 0.3],
pos: [0, 0],
});
spaceShip.animate([
{pos: [0, 0]},
{pos: [0, 75]},
{pos: [600, 100]},
{pos: [600, 50]},
], {
duration: 4000,
iterations: Infinity,
direction: 'alternate',
});
layer.append(spaceShip);
}
})();