nswdpc / silverstripe-async-loader
使用loadjs的Silverstripe 4异步资源加载器
Requires
- silverstripe/framework: ~4.0
Requires (Dev)
- phpunit/phpunit: ^3 || ^4 || ^5
This package is auto-updated.
Last update: 2024-09-11 07:46:48 UTC
README
此模块提供使用loadjs异步加载需求的后端
目标是使需求加载轻量级,不阻塞页面加载,并支持关键需求和非关键需求的分离。
loadjs自身作为页面内的内联脚本加载
支持Silverstripe 4.0+
使用示例
use SilverStripe\View\Requirements;
use NSWDPC\AsyncLoader\Backend as AsyncRequirementsBackend;
$backend = new AsyncRequirementsBackend();
Requirements::set_backend($backend);
// load requirements in the default bundle (blocking)
Requirements::javascript('path/to/some/requirement.js');
Requirements::javascript('https://example.com/lib_depending_on_requirement.js');
Requirements::javascript('//example.com/load_over_current_protocol.js');
// block requirements as usual
Requirements::block('/something_you_want_to_block.js');
// create a specific bundle
$backend->bundle('fontawesome', ['https://use.fontawesome.com/fa_code.js']);
捆绑
loadjs使用依赖项'bundles'来管理脚本的加载。
默认需求捆绑
为了向后兼容,通过Requirements::javascript
加载的脚本将通过loadjs顺序加载,并分配给捆绑包'requirements_bundle'
参见loadjs文档的第3节
一旦所有脚本都加载完毕,将触发一个回调loadjs_ready_requirements_bundle
,并触发一个DOM事件load_requirements_bundle
需要加载脚本后再触发的自定义脚本可以监听此DOM事件
document.addEventListener('load_requirements_bundle', function(e) {
// custom script
}
特定捆绑
不依赖于默认捆绑包中加载的任何内容的脚本可以以非阻塞方式在其自己的捆绑包中加载
// load fontawesome
$backend->bundle('fontawesome', ['https://use.fontawesome.com/fa_code.js']);
可选地带有回调...如果需要在捆绑包加载后执行某些操作
参见loadjs文档的第1节
// load fontawesome
$backend->bundle('fontawesome', ['https://use.fontawesome.com/fa_code.js'], "console.log('fontawesome loaded!');");
您可以在捆绑包中包含多个脚本
参见loadjs文档的第2节
// load one and two asynchronously (two.js may load before one.js)
$backend->bundle('fontawesome', ['/script/one.js','/script/two.js']);
CSS
CSS需求默认以阻塞模式通过<head>
标签加载。
您可以通过后端捆绑包以非阻塞模式加载CSS
// load CSS without blocking
$backend->bundle_css('css_bundle', ['path/to/style.css']);
请注意,除非您加载了设置基本/可接受的上卷布局的样式,否则您很可能会在样式表应用之前遇到FOUC。这很快,但很丑。
请参阅loadjs文档的第5节关于CSS加载的说明。
页面位置
如果您愿意,将HTML注释<!-- asyncloader_script_requirements_placeholder -->
放置在您的页面模板中,您希望在其中放置JS需求的位置。后端将用找到的JS需求替换此注释。如果您不这样做,JS需求将在关闭body标签之前加载。
自定义脚本
如果您有假设库已加载的自定义脚本,除非它们在依赖项加载后运行,否则它们很可能失败。为了确保它们正确运行,请在相关的捆绑包回调或load_requirements_bundle
的事件监听器中应用它们。
自定义head标签
这些在关闭head标签之前加载。
待办事项
- 对于非关键CSS,支持'lazy'加载Requirements::css()放置在关闭body标签之前的
<link>
标签。
许可证
BSD 3-Clause
- loadjs根据MIT许可证授权:https://github.com/muicss/loadjs/blob/master/LICENSE.txt