Adding external JavaScript file in Laravel | How to include ExternalJS file in Laravel

To include an external JavaScript file in a Laravel application, you can follow these steps:

  1. Download or reference the External JavaScript File:

    Obtain the external JavaScript file you want to include in your Laravel application. You can either download it and place it in a specific directory within your Laravel project or reference it directly from an external source (e.g., a CDN).

  2. Option 1: Place JavaScript File in the public Directory:

    If you downloaded the external JavaScript file, you can place it in the public directory of your Laravel project. For example, you can create a new directory called js inside public and place your JavaScript file there:

    kotlin
  • public ├── js │ └── external.js
  • Option 2: Link to External Source (CDN):

    If you prefer to reference an external JavaScript file from a Content Delivery Network (CDN), you can include it directly in your Blade view or layout file. For example, to include jQuery from a CDN, you can add the following to your Blade view file:

    html
  • <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  • Include JavaScript File in Blade View:

    Open the Blade view file where you want to include the external JavaScript file. You can include it using the asset helper function if the file is in your public directory, or you can use a full URL if you're referencing an external source.

    For example, to include an external JavaScript file named external.js located in the public/js directory:

    html
  • <script src="{{ asset('js/external.js') }}"></script>

    Or, to include an external JavaScript file from a CDN:

    html
  • <script src="https://example.com/path/to/external.js"></script>

    Ensure that you place this <script> tag in the <head> or at the end of the <body> section of your Blade view file, depending on when you want the JavaScript file to be loaded and executed.

  • Clear Cache (if necessary):

    If you have caching enabled in your Laravel application, you may need to clear the cache to see the changes take effect. You can clear the cache using the following Artisan command:

    bash
    1. php artisan cache:clear

      Additionally, you can use the php artisan view:clear command to clear the compiled Blade views.

    By following these steps, you can successfully include an external JavaScript file in your Laravel application, either by placing it in the public directory or by referencing it directly from an external source.

    Comments