Running a JavaScript as an external script in Laravel

Viewed 461

I have a blade code like this:

<input type='text' id="input1">
<div >
 <h3 id="showData"> Data will be shown here  </h3>

</div>

<script>
  var input=document.getElementById('input1').value;

  document.getElementById('showData').innerHTML=input;
</script>

What I want is to write the script part in a separate file (say called externalScript.js) and call it here in the blade file.

Also, I have a doubt about it. If I do that, since the script is run from an external file, how will it fetch the id values like input1 or showData ?

2 Answers

Write a new file called: externalScript1.js

Add the script tag, best in the head or foot part of your code.

    <script src="{{ asset('externalScript1.js') }}" defer></script>

(the asset helper gets the path to the public folder, https://laravel.com/docs/8.x/helpers#method-asset)

In the end everything will load from one page, ergo the elements are found, so you won't have a problem.

Just add js file in laravel resources directory, link to webpack and compile more info.

when it comes to executing the script, attach it at the end of the page (before </body>) or wait for the page to be loaded document.addEventListener('DOMContentLoaded', function() {})

Attach the js file in the main wrapper, not in the nested blade element

Related