Search code examples
javascriptjquerynode.jsnpmbrowserify

jquery appears in browserify bundle.js but not working in browser


I'm following this short tutorial on getting started with Browserify Getting Started with Browserify. Despite following everything exactly jquery isn't working on the page when bundled,ie. the button element in my app.js code below is not appended to the body. Have checked everything I can think of using chrome dev tools to make sure all is loading ok, which it is.The bundle.js loads fine and my jquery code from app.js is in it. Also the alert() and console.log() output fine so I know the jQuery is specifically being ignored. Tried changing the jquery version to that of the tutorial but still doesn't work. I know the jQuery code itself is fine because it works when I add the code directly on the index page and link to directly to the jquery.js inside node_modules directory. Any ideas what might be the problem?Thanks in advance!

app.js

var $ = require('jquery')
alert("hi from app.js") // this appears in browser on page load

// none of this jQuery currently works using Browserify
var button = $('<button/>').html('click me').on('click', function() {
alert("hi from browserify!")
})
$('body').append(button)

console.log("where is jQuery code ....."); // this logs in dev console

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Browserify Test with jQuery</title>
    <script src="bundle.js" charset="UTF-8"></script>
<!--<script src="node_modules/jquery/dist/jquery.js"></script>-->
  </head>
  <body>
  <!--<script>
    var button = $("<button/>").html("click me").on("click", function() {
    alert("hi from browserify!")
    })
   $("body").append(button)
  </script>-->
</body>
</html>

Here is the code as it appears in the bundle.js file created by Browserify.

......// rest of bundle.js 
},{}],2:[function(require,module,exports){
var $ = require('jquery')
alert("hi from app.js")

var button = $('<button/>').html('click me').on('click', function() {
alert("hi from browserify!")
})
$('body').append(button)

console.log("where is jQuery code .....");

},{"jquery":1}]},{},[2]);

package.js

{
"name": "browserify-test",
"version": "1.0.0",
"description": "Testing Browserify",
"main": "index.js",
"scripts": {
  "build": "browserify app.js -o bundle.js",
  "watch": "watchify app.js -o bundle.js"
},
"author": "MikeM",
"license": "ISC",
"devDependencies": {
"browserify": "^10.2.3",
"jshint": "^2.8.0",
"watchify": "^3.2.1"
},
"dependencies": {
  "jquery": "^2.1.4"
}
}

Solution

  • I had the same issue. Find out I load bundle.js in head, when DOM is not ready. Try to wrap your code in $(function(){...//code here...}) or move bundle.js to the end of body.