From 9a5d14aa1309dd94708d9d59ecee0702ca3eda19 Mon Sep 17 00:00:00 2001 From: Andy Miller Date: Mon, 2 Mar 2015 11:03:21 -0700 Subject: [PATCH] Added async and defer loading of JavaScript files --- system/src/Grav/Common/Assets.php | 38 +++++++++++++++++++++++++++---- 1 file changed, 34 insertions(+), 4 deletions(-) diff --git a/system/src/Grav/Common/Assets.php b/system/src/Grav/Common/Assets.php index 70bc73dde..57830fb95 100644 --- a/system/src/Grav/Common/Assets.php +++ b/system/src/Grav/Common/Assets.php @@ -265,10 +265,11 @@ class Assets * @param mixed $asset * @param int $priority the priority, bigger comes first * @param bool $pipeline false if this should not be pipelined + * @param string $loading how the asset is loaded (async/defer) * * @return $this */ - public function addJs($asset, $priority = 10, $pipeline = true) + public function addJs($asset, $priority = 10, $pipeline = true, $loading = '') { if (is_array($asset)) { foreach ($asset as $a) { @@ -290,13 +291,42 @@ class Assets 'asset' => $asset, 'priority' => $priority, 'order' => count($this->js), - 'pipeline' => $pipeline + 'pipeline' => $pipeline, + 'loading' => $loading ]; } return $this; } + /** + * Convenience wrapper for async loading of JavaScript + * + * @param $asset + * @param int $priority + * @param bool $pipeline + * + * @return \Grav\Common\Assets + */ + public function addAsyncJs($asset, $priority = 10, $pipeline = true) + { + return $this->addJs($asset, $priority, $pipeline, 'async'); + } + + /** + * Convenience wrapper for deferred loading of JavaScript + * + * @param $asset + * @param int $priority + * @param bool $pipeline + * + * @return \Grav\Common\Assets + */ + public function addDeferJs($asset, $priority = 10, $pipeline = true) + { + return $this->addJs($asset, $priority, $pipeline, 'defer'); + } + /** * Add an inline CSS asset. * @@ -450,11 +480,11 @@ class Assets if ($this->js_pipeline) { $output .= '' . "\n"; foreach ($this->js_no_pipeline as $file) { - $output .= '' . "\n"; + $output .= '' . "\n"; } } else { foreach ($this->js as $file) { - $output .= '' . "\n"; + $output .= '' . "\n"; } }