如何在 Magento 中使用 head.js 或 labjs 等 JavaScript 加载器
Magento 立即附带了六个以上的 JavaScript 库,这些库对本已很麻烦的加载时间没有任何帮助。有没有人能够成功地在 Magento 中使用像 head.js 或 labjs 这样的脚本加载器,以便它们可以异步加载?我一直在尝试但无法让它发挥作用。
似乎页面上的内联脚本在加载库之前就已触发。我知道 head.js 有一个像 head.ready 这样的函数来告诉脚本执行,但是有很多内联脚本,将其添加到整个站点中的每个事件中是不切实际的。
Off the bat Magento comes with more than half a dozen JavaScript libraries which do not help with the already cumbersome load times. Has anybody been able to successfully use a script loader like head.js or labjs with Magento so that they can load asynchronously? I have been trying but can't get it to work.
Seems as though the in-line scripts on the pages are firing before the libraries are loaded. I know that head.js has a function like head.ready to tell a script to execute , but there are so many in-line scripts it is not practical to add this to every occurrence in the whole site.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于内联脚本,有一个编程解决方案。
您可以编写一个观察者,绑定到
core_block_abstract_to_html_after
或controller_action_layout_render_before
事件,这些事件在输出渲染的 HTML 之前立即触发。在 Observer 中,您可以使用preg_replace
在每个标记之后立即插入
head.ready
语句。它会增加渲染时间的一小部分,但我怀疑它会少于下载库的延迟。如果您使用全页缓存,则该函数只会被调用一次。
您可以使用内置的 Magento Profiler 来测试影响。至少值得一试。
HTH,
京东
Regarding the inline scripts, there is a programmatic solution.
You could write an Observer that binds to the
core_block_abstract_to_html_after
orcontroller_action_layout_render_before
Events which fire immediately prior to outputting the rendered HTML. In your Observer, you could use apreg_replace
to insert ahead.ready
statement immediately after each<script>
tag.It would add a fraction more to the render time, but I suspect it would be less than the latency of downloading the libraries. And if you're using full page caching, then the function would only be called once.
You could use the inbuilt Magento Profiler to test the impact. Worth a try at least.
HTH,
JD
好吧,我为此使用jquery。而且效果很好。
您所要做的就是发出一个返回脚本的 ajax 请求,然后使用
eval
评估脚本。您可以为此编写自己的函数,但 jquery 已经有一些不错的方法。对于单个脚本,
$.getScript
函数效果很好。它基本上是$.ajax
函数的扩展,指定您正在请求脚本。语法是这样的:如果你想通过ajax添加更多脚本,jquery有一个neet方法可以做到这一点:
well, i use jquery for this. and it works great.
All you have to do is to make an ajax request that returns the script and then evaluate the script using
eval
. You can write your own function for this, but jquery already has some nice approaches.For single scripts, the
$.getScript
function works well. It's basically an extension of the$.ajax
function that specifies that you are requesting a script. the syntax is like this :If you have more scripts that you want to add through ajax, jquery has a neet way of doing this :
所有这种性质的加载器都需要对站点上的每个脚本进行一些修改。我知道——我刚刚在一个系统上实现了 LABjs,当我 grep 时,它显示了 400 多个带有某种脚本标签的文件!
All loaders of this nature are going to require some modification to every script on your site. I know--I just implemented LABjs on a system which, when I grepped, showed over 400 files with some sort of script tag!!