1

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.

0

3 Answers 3

4

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!');
};
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Ross, that nailed it. But why? Why do I need to assign it to the window just because it is coming from a different file?
@KimPrince This is simply down to scope. scotch.io/tutorials/understanding-scope-in-javascript. My wording of this might be a bit off but essentially webpack will create a bundle from your code which will be made up of one or many modules. When you define a function in this way it will only be able to the scope of that module e.g. function a() { function b() {}} you would only be able to call b(); from inside a();
Thanks Ross, that makes sense.
0

have you tried to use asset() function?

<script src="{{asset('/dist/js/full-feature-detect.js')}}"></script>

Comments

0

Just add in body:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.