1

I want to include an external Javascript(with jQuery) to reactjs.

I did take a look to this, but there are still some error.

I have a external JS file, called external.js:

$(document).ready(function() {
    document.addEventListener("deviceready", onDeviceReady, 
});


function onDeviceReady() {
    console.log("The device is ready");
}

In index.html, i add the <script src="external.js"></script> to the script:

<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="theme-color" content="#000000">
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json">
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    <title>React App</title>
  </head>
  <body>
    <noscript>
      You need to enable JavaScript to run this app.
    </noscript>
    <script src="external.js"></script>
    <div id="root"></div>
  </body>
</html>

Inside the React js project, I added the following code to App.js:

import * as jQuery from 'jquery';
window.$ = jQuery;

However, when I run the reactJS project with command npm start, inside the console, it shows

external.js:1 Uncaught ReferenceError: $ is not defined

What should I do in order to include the external js file and also the jQuery?

VICTOR
  • 1,894
  • 5
  • 25
  • 54
  • Are you using webpack? – orabis Jan 08 '18 at 07:17
  • I am using npm for building the React js app – VICTOR Jan 08 '18 at 07:26
  • So, you don't have a webpack.config file? – orabis Jan 08 '18 at 07:27
  • I don't have `webpack.config` file – VICTOR Jan 08 '18 at 07:36
  • Are you able to show us your index.html file? – orabis Jan 08 '18 at 07:39
  • I know the reason behind your problem. App.js is called after the document load or at least after the call for external.js script. It will be helpful to take a look at the index.html file to think of the best solution. – orabis Jan 08 '18 at 07:42
  • Updated the question with the index.html file – VICTOR Jan 08 '18 at 07:44
  • you are only including one script (external.js) in your html file? Where is the main script of your app? – orabis Jan 08 '18 at 07:46
  • Actually Im very new to React JS. There are two more js files: App.js and index.js. When I type `npm start`, it will automatically compile the code. – VICTOR Jan 08 '18 at 07:53
  • 1
    Which one of them depends on the other one? I am guessing index.js is your root script? If so, I would like you to add a script tag, and reference to this script, and make sure that it comes before the external.js script element. – orabis Jan 08 '18 at 07:54
  • Thanks, it works after putting the include jquery before including the external js – VICTOR Jan 08 '18 at 07:56

1 Answers1

1

Your external script is executed before the statement window.$ = jQuery. Try to include the jQuery (before the inclusion of the external script) like you included the external script

Alexander Elgin
  • 6,796
  • 4
  • 40
  • 50