inline-script.md 1.87 KB
Newer Older
Ketan's avatar
Ketan committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
# InlineScript

The HTML `<script>` element is used to either provide inline client-side
scripting elements or link to a remote resource containing client-side scripting
code. The `InlineScript` helper allows you to manage both. It is derived from
[HeadScript](head-script.md), and any method of that helper is available;
replce the usage of `headScript()` in those examples with `inlineScript()`.

> ### Use InlineScript for HTML body scripts
>
> `InlineScript` should be used when you wish to include scripts inline in the
> HTML `<body>`.  Placing scripts at the end of your document is a good practice
> for speeding up delivery of your page, particularly when using 3rd party
> analytics scripts.  Some JS libraries need to be included in the HTML
> `<head>`; use [HeadScript](head-script.md) for those scripts.

## Basic Usage

Add to the layout script:

```php
<body>
    <!-- Content -->

    <?php
    echo $this->inlineScript()
        ->prependFile($this->basePath('js/vendor/foundation.min.js'))
        ->prependFile($this->basePath('js/vendor/jquery.js'));
    ?>
</body>
```

Output:

```html
<body>
    <!-- Content -->

    <script type="text/javascript" src="/js/vendor/jquery.js"></script>
    <script type="text/javascript" src="/js/vendor/foundation.min.js"></script>
</body>
```

## Capturing Scripts

Add in your view scripts:

```php
$this->inlineScript()->captureStart();
echo <<<JS
    $('select').change(function(){
        location.href = $(this).val();
    });
JS;
$this->inlineScript()->captureEnd();
```

Output:

```html
<body>
    <!-- Content -->

    <script type="text/javascript" src="/js/vendor/jquery.js"></script>
    <script type="text/javascript" src="/js/vendor/foundation.min.js"></script>
    <script type="text/javascript">
        //<!--
        $('select').change(function(){
            location.href = $(this).val();
        });
        //-->
    </script>
</body>
```