PJAX成功后执行页面特定的JavaScript代码 [英] Execute page-specific javascript code after PJAX success

查看:125
本文介绍了PJAX成功后执行页面特定的JavaScript代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的难题:

我的网站使用PJAX将HTML加载到每个页面的#main容器中。

My website uses PJAX to load HTML into the '#main' container for each page.

每个页面都有自己的特定javascript文件。例如:dashboard.index.js,inbox.index.js等。
注意:所有库都通过PreloadJS预先载入页面,以避免javascript编译开销。

Each page has its own specific javascript file. E.g: 'dashboard.index.js', 'inbox.index.js' and so on. Note: All libraries are preloaded on the first load of the page through PreloadJS to avoid javascript compilation overhead.

页面的第一个加载是完美的,没有担心,因为它是一个正常的HTML加载。

The first load of the page is perfect, no worries, since it is a normal HTML load.

但是如果我再次回到这个页面,PJAX将不会重新加载javascript文件,因为它已经在DOM 。

However if i come back to this page again, PJAX won't reload the javascript file, given it's already in the DOM.

没有完美的工作:


  1. 将javascript文件放在'main'容器的底部。 PJAX将其传输到DOM的HEAD,并且不会再次加载它。

  2. 将line脚本放在main容器中以执行每个页面的功能。在加载JS库之前,代码执行失败。

  3. 绑定PJAX成功事件和执行功能。无法确定基于当前加载页面执行的功能。

因此,我的问题:

是否有任何策略来加载与每个页面相关联的特定JavaScript文件?

Is there any strategy to load specific javascript files associated to each page?

推荐答案

从pjax加载HTML ,我添加了一个'data-js'属性到div,其中包含要成功加载HTML的函数的名称。

When loading HTML from pjax, i added a 'data-js' attribute to the div, which contained the name of the function to call upon successfully loading HTML.

然后只是使用'pjax:success'事件调用函数。

Then it was just a matter of using the 'pjax:success' event to call the function.

这篇关于PJAX成功后执行页面特定的JavaScript代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆