Call javascript function from each page load without any change in other html page

Viewed 98

I have a requirement to call a java script function onload of each html page but need to add onload="fun()" code in all the form around 200.

Is there any other way to do change in one place and it will automatically plugin all form and at the time of form load my function get call.

4 Answers

Could you try this ;

document.addEventListener("DOMContentLoaded", function() {
  you_function(...);
});

You can check on html load all the form in the page and attach events to those forms:

document.addEventListener("DOMContentLoaded", function() {
  for(var i=0; i<document.forms.length; i++){
    var form = document.forms[i];
    form.addEventListener("load", fun, false);
  }
});

I want to point out although that form has not "onload" event.

You could use jQuery for this purpose:

If you use jQuery (as a lot of people do) you can avoid browser inconsistency between things like window.onload and document.onload and leave your framework doing this for you:

$(document).ready(function() { /* code here */ });

If your problem is different than seemingly most understand and you want to insert your function call into "arround 200 forms" you could consider using refactoring tools of your favourite IDE and replace any <script> you use in your documents with the same script plus your additional function call.

There are some way to accomplish that but the best one, I think so, is using a template engine such as smarty, pug, or what template engine you are comfortable with, and create a layout on which your function resides and finaly make all html pages to extend that layout.

Related