javascriptlaravel

Can not run JS code with a Laravel Blade stack


This code runs:

@push('scripts')
    <script>
        function esFeatureDetect() {
            console.log('Feature detection function has been called!');
        }
    </script>
@endpush

@push('scripts')
    <script>
        esFeatureDetect();
    </script>
@endpush

The problem is that if I take the function and put it in another file (using webpack), suddenly the function is not found.

Here is what the code looks like in the external file:

function esFeatureDetect() {
    console.log('Feature detection function has been called!');
}

Webpack bundles it fine. (I use Webpack for many other files too).

Here are the new blade directives:

@push('scripts')
    <script src="/dist/js/full-feature-detect.js"></script>
@endpush

@push('scripts')
    <script>
        esFeatureDetect();
    </script>
@endpush

But I get an error saying that:

esFeatureDetect is not defined

Why is it so?

The file is being pulled into the browser file, I can see the code in the console. I also tried the following call:

window.onload = esFeatureDetect;

and

window.onload = esFeatureDetect();

but neither helped.


Solution

  • If you want to be able to use you function in the global scope you'll need to attach it to the window object.

    window.esFeatureDetect = function () {
        console.log('Feature detection function has been called!');
    };