RegisterPackage depends on RegisterScriptFile

2020-04-08 12:54发布

问题:

I have a package that requires Google Map library. And I implemented it like this in the view.

<?php Yii::app()->clientScript->registerScriptFile('http://maps.googleapis.com/maps/api/js?sensor=false&language=' . Yii::app()->language . '&region='.Yii::app()->language, CClientScript::POS_HEAD); ?>
<?php Yii::app()->clientScript->registerPackage('somelibrary'); ?>

(Note that the Google Map library needs a parameter Yii::app()->language).

But in the output, the package is always placed above the google maps.

<script type="text/javascript" src="/project/assets/74e60422/somelibrary.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&amp;language=id&amp;region=id"></script>

Is there any solution to make the Google Maps library as the package dependency? Or, at least, how to place the somelibrary package right after (not far below) the google maps ?

回答1:

You can make the google map script a package itself by configuring the packages property of CClientScript. Then you can add the googlemap to your packages dependencies by configuring 'depends' in the package configuration. This should then add the scripts in the correct order.

To add a package you can do the following (didn't try that, but should work):

Yii::app()->clientScript->addPackage('googleMap', array(
    'baseUrl'=>'http://maps.googleapis.com/maps/api',
    'js'=>array('js?sensor=false&language=' . Yii::app()->language . '&region='.Yii::app()->language)
));

Same 'googleMap'=>array(/*...*/) will work when you put it in your configuration.



回答2:

registerPackage() method don't have the any option to decide its position but you can decide position of registerScriptfile() like this ...

public CClientScript registerScript(string $id, string $script, integer $position=4)

$position integer the position of the JavaScript code. Valid values include the following: CClientScript::POS_HEAD : the script is inserted in the head section right before the title element. CClientScript::POS_BEGIN : the script is inserted at the beginning of the body section. CClientScript::POS_END : the script is inserted at the end of the body section. CClientScript::POS_LOAD : the script is inserted in the window.onload() function. CClientScript::POS_READY : the script is inserted in the jQuery's ready function.



标签: php yii