Yii2: Registering Asset Bundle vs registering external Js file

前端 未结 3 438
你的背包
你的背包 2020-12-10 14:52

Hi I wanted to know the advantage of registering Asset Bundle following the process described in the docs like Process one in AppAsset.php

p         


        
相关标签:
3条回答
  • 2020-12-10 15:15

    One of the main reasons for using an Asset Bundle is that your assets' paths will always be correct. Consider:

    $this->registerJsFile('js/myjsfile.js', ['position'=>$this::POS_READY]);
    

    will generate something like:

    <script src="js/myjsfile.js"></script>
    

    Which works great for non urlManager enabled urls, e.g. http://localhost/yiiproject/index.php?r=user/update&id=8 because your browser looks for the js file at: /yiiproject/js/myjsfile.js

    But if you enable urlManager, your url will look like http://localhost/yiiproject/user/update/8, which means your browser will look for your js file at: /yiiproject/user/update/8/js/myjsfile.js.

    You could overcome this problem by using:

    $this->registerJsFile(Yii::$app->request->baseUrl.'/js/myjsfile.js', ['position'=>$this::POS_READY]);
    

    But the Asset Bundle basicly does that for you.

    0 讨论(0)
  • 2020-12-10 15:19

    Asset Bundles have some advantages over normal registering. Apart from what @deacs said in his/her answer here are others:

    1. Assets Bundles can publish the file to assets if its not in web accessible directory
    2. Assets Bundle can deal with less files (in case of CSS) as well as compressing the assets.
    3. Makes Code Elegant especially in solving dependencies and hence reusability

    All the features that makes bundles shine are found in docs

    0 讨论(0)
  • 2020-12-10 15:28

    Using Asset Bundles, you can also get the latest version from 'vendor' folder, so if you need to update some lib you don't need to manually do this since composer already do this.

    0 讨论(0)
提交回复
热议问题