Add an external JavaScript library to a view in Yii2 that depends on jQuery Asset

In this short demo, we will take an example of jQuery Sortable Plugin. We will add the jQuery UI library directly to a view. Alternative approach to this method would be to install jQuery UI using composer and add related assets in the AssetBundle.

To add an external JS file, we would use Yii2 function registerJsFile($url, $options = [], $key = null)

<?php 
$this->registerJsFile('//code.jquery.com/ui/1.12.1/jquery-ui.min.js',['depends' => [\yii\web\JqueryAsset::class()]]);
?>

To specify the position where this library should load i.e. in the head, beginning of the body, end of the body, we may use yii\web\view::POS_{LOCATION} constant. Check constants section of yii\web\view.

<?php 
$this->registerJsFile('//code.jquery.com/ui/1.12.1/jquery-ui.min.js',['depends' => [\yii\web\JqueryAsset::class()], 'position'=>[\yii\web\view::POS_HEAD]]);
?>

Running low on budget? Get the best Shared hosting at an Affordable Rate!