0

I intend to use a JavaScript library on my WP website and have uploaded the JS file via FTP to the following directory belonging to the currently activated theme Salient: /public_html/wp-content/themes/salient/js

Then, in order to load the JavaScript, I have added the following line in the "Header and Footer" settings (to be injected before the body closing tag):

<script type="text/javascript" src="https://www.mypage.../public_html/wp-content/themes/salient/js/javascriptfile.js"></script>

When I am then loading a page and when inspecting it using the Chrome console, there's a 404 error for that JS file, although the file and the directory exist. As an alternative approach I also tried to add the script reference directly in HTML and even the page template, but with the same result.

Why do I keep getting the 404 error? Thanks for your help.

1

You should enqueue your script using

wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer);

Where,
$handle is the name for the script.

$src defines where the script is located.

$deps is an array that can handle any script that your new script depends on, such as jQuery.

$ver lets you list a version number.

$in_footer is a boolean parameter (true/false) that allows you to place your scripts in the footer of your HTML document rather then in the header, so that it does not delay the loading of the DOM tree.

Documentation

Add this code to functions.php file of your theme.

function add_my_script() {

  wp_enqueue_script( 'my-script', 
         get_template_directory_uri() . '/js/javascriptfile.js', 
         array ( 'jquery' ), 
         false,
         true
  );

}
add_action( 'wp_enqueue_scripts', 'add_my_script' );
  • Thank you Qaisar. I added the code to functions.php. There's no 404 error in the console, but when looking at the source code I cannot find the JS file added/referenced. – F.Marks Apr 13 at 19:06
  • Look for it somewhere just before closing </body> tag. If it is a on a live/online site please share link so I may help find it. – Qaisar Feroz Apr 13 at 19:13
  • I found it, it was n't in because of a different error in functions.php which I have now also fixed, thanks Quaisar, I appreciate your kind help! I was very specific with my question and I am not a professional programmer, it is sad to see that someone downvoted my question (I do not assume it was you). Thanks so much again!! Frank – F.Marks Apr 13 at 19:22
  • Stay blessed always! I don't know why someone down-voted your question, but I up-voted it just now. – Qaisar Feroz Apr 13 at 19:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.