0

我确实通过htmx更新了一个 html 片段。

如何加载这个新片段所需的 JS 库?

代码片段加载后如何执行函数?

例子:

在将 html 片段添加到页面后,我想显示一个快乐的动画(五彩纸屑)。

这意味着浏览器需要加载这个:

<script src="https://cdn.jsdelivr.net/npm/canvas-confetti@1.4.0/dist/confetti.browser.min.js"></script>

加载上述 lib 之后,需要执行一个 JS 函数。

如何用 htmx 做到这一点?

4

2 回答 2

1

目前无法在 htmx 内置的页面上加载新库(这是 IMO 的必要功能,请为它记录问题),因此 confetti 库最初应包含在您的主站点中。

在主网站中包含外部库后,您可以包含一个普通script标签,该标签执行内联所需的五彩纸屑代码:

<script>
var myCanvas = document.createElement('canvas');
document.appendChild(myCanvas);

var myConfetti = confetti.create(myCanvas, {
  resize: true,
  useWorker: true
});
myConfetti({
  particleCount: 100,
  spread: 160
  // any other options from the global
  // confetti function
});
</script>
于 2021-04-15T13:32:57.540 回答
1

我找到了解决方案。我想它可以得到改善。如果您知道更简单的方法,请发表评论。

// lala.js 
// this file gets loaded in the page (before the hx-post call)

function loadScript(url, callback) {
    // https://stackoverflow.com/a/950146/633961
    // Adding the script tag to the head as suggested before
    var head = document.head;
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;

    // Then bind the event to the callback function.
    // There are several events for cross browser compatibility.
    script.onreadystatechange = callback;
    script.onload = callback;

    // Fire the loading
    head.appendChild(script);
};

document.body.addEventListener("confetti", function(evt){
    var target = document.getElementsByClassName('htmx-settling')[0];
    loadScript('https://cdn.jsdelivr.net/npm/canvas-confetti@1.4.0/dist/confetti.browser.min.js',
        function () {
            var myCanvas = document.createElement('canvas');
            var rect = target.getBoundingClientRect();
            myCanvas.setAttribute('style', 'position: absolute; top:' +
                rect.top + 'px; left:' + rect.left + 'px');
            target.appendChild(myCanvas);

            var myConfetti = confetti.create(myCanvas, {
                resize: true,
                useWorker: true
            });
            myConfetti({
                particleCount: 100,
                spread: 160
                // any other options from the global
                // confetti function
            })
        })
})

在服务器端,我返回这样的响应(Django):

def confetti_hx(request):
    ...  
    response = HttpResponse(html)
    response['HX-Trigger-After-Swap'] = 'confetti'
    return response
于 2021-04-15T19:43:29.483 回答