简体   繁体   中英

How to make addEventListener work for Javascript functions in a separate file?

I currently have document.addEventListener('DOMContentLoaded', functionName); which passes the following function as the parameter:

function functionName() {
  $.ajax({
    type: 'GET',
    url: '/populatePage',
    success: function(data) {
      createPage(data);
    }
  })
}

Problem Description:

When the function above is in the same javascript file as the line document.addEventListener('DOMContentLoaded', functionName); the page loads properly.

But when the function is saved in a separate javascript file and then included in the file with the line above, the page does not load.

I'm probably missing something basic here, but can anyone please explain?

Make it global function. It's not advisable but if you want quick solution then

window.functionName = function() {
  $.ajax({
    type: 'GET',
    url: '/populatePage',
    success: function(data) {
      createPage(data);
    }
  })
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM