jpwalker
jpwalker

Reputation: 33

How to avoid js function overwritten when loading page from ajax.

For example:

--- a.php ---
<script>
function fun() {
   console.log('this is fun() from a.php');
}
function loadb() {
   $("#loadb").load("b.php");
}
function removeb() {
   $("#loadb").remove();
}
</script>
This is a.php
<input type="button" onclick="fun()" value="echo fun">
<input type="button" onclick="loadb()" value="load b.php">
<input type="button" onclick="removeb()" value="remove b.php">
<div id="loadb"></div>

--- b.php ---
<script>
function fun() {
   console.log('this is fun() from b.php');
}
</script>
This is b.php

After I loaded b.php from Ajax, the "fun()" in a.php will overwritten even when I removed the b.php by removing the , the fun() in b.php still keep in page.

What is the practical way to ensure the ajax-ed page will call it's own js function?

Cos a.php will load many other pages which develop by different developer They might write their own js function inside the page, and sometimes their function will have common naming, like: remove(), add()... etc.

I want to know, if there any efficient way to avoid this?

Thanks.

Upvotes: 2

Views: 511

Answers (1)

Samuel Rossille
Samuel Rossille

Reputation: 19858

The answer is a plain simple no.

As a consequence of what the browser does when a script tag is appended to the DOM there is no way to protect a function from being overwritten by some assignation made by the script.

You really have no realistic other solutions than to properly to that in each module:

  1. Properly namespace your public functions in each module
  2. Scope your private functions in each module, with the Self Executing Function pattern

Upvotes: 1

Related Questions