Skip to content Skip to sidebar Skip to footer

Javascript One Function Name In Multiple Files

What I need is pretty simple, although I don't know if possible.. I'm attaching all my event handlers to the object themselves instead of to $(document). But, I need to attach them

Solution 1:

But.. this function should execute codes that are in multiple files.

My question is.. is there a way of declaring the same function multiple times, and then calling it just once to execute them all?

If interpret Question correctly, you want to request javascript from multiple files at .ready() . You can create an array containing url of file to request, use $.when(), $.map(), $.getScript() to call the javascript within the files

jQuery.getScript( url [, success ] ) Returns: jqXHR Description: Load a JavaScript file from the server using a GET HTTP request, then execute it.

The script is executed in the global context, so it can refer to other variables and use jQuery functions. Included scripts can have some impact on the current page.

$(document).ready(function() {

var files = ["1.js", "2.js", "3.js"];

  $.when.apply($, $.map(files, function(file) {
    // request filereturn $.getScript(file)
  }))
  .then(function() {
    // complete// do stuff
  }, functionerr(jqxhr, textStatus, errorThrown) {
    // handle error
  });

});

Solution 2:

Create a global JS file that has this function (and future functions that you want to be run on all pages). Call this script at the top of each file in the head element. Calling it in the head should do what you need (at least that is what i use in my projects and works for me).

Solution 3:

Can u package your multiple files in modules and every one of them has a method attachHandlers? Then try use requirejs to load all of them. In document.ready, call the attachHandlers method from all these modules? It will be neater

Post a Comment for "Javascript One Function Name In Multiple Files"