Joomla异步脚本加载jdoc头


Joomla asynchronous script loading jdoc head

我正在使用Joomla!3.4

<jdoc:include type="head">调用/libraries/joomla/document/html/renderer/中的head.php文件,其中可以在生成脚本文件链接的部分中找到对$strAttr['async']的引用。

$strAttr只是foreach循环命名的数组,但它来自$document->_scripts

我想异步加载脚本,如何更改每个脚本文件的属性$strAttr['async']?我知道我可以更改head.php中的代码,但我认为我忽略了Joomla中的一些设置。

如果要对每个脚本文件执行此操作,则必须编写一个系统插件并实现函数onBeforeCompileHead()

在这个功能中,你需要这样的东西:

/**
 * possible implementation of onBeforeCompileHead
 * to make all the scripts async.
 */
public function onBeforeCompileHead() {
    $document = JFactory::getDocument();
    foreach ($document->_scripts => $url) {
        $document->_scripts[$url]['async'] = true;
    }
}

相反,如果您只想制作应用程序或模板的js,请使用JDocument::addScript();像这样:

/**
 * Possible implementation to insert a async script in a component or a module. 
 * @see JDocument::addScript($url, $type = "text/javascript", $defer = false, $async = false)
 */
$document = JFactory::getDocument();
$document->addScript('/media/system/js/sample.js', "text/javascript", false, true);