Если вы хотите загрузить Javascript по требованию. Это можно сделать путем динамического создания тега скрипта. Этот образец проиллюстрирован в Стоян Стефанов книга - Шаблоны Javascript
Это вырезано из книги:
Напишите требуемую функцию. Затем назовите это так:
require("extra.js", function () {
functionDefinedInExtraJS();
});
Образец требует функции:
function require(file, callback) {
var script = document.getElementsByTagName('script')[0],
newjs = document.createElement('script');
// IE
newjs.onreadystatechange = function () {
if (newjs.readyState === 'loaded' || newjs.readyState === 'complete') {
callback();
}
};
// others
newjs.onload = function () {
callback();
};
newjs.src = file;
script.parentNode.insertBefore(newjs, script);
}
Живой пример найден в http://www.jspatterns.com/book/8/ondemand.html
@ Редактировать: подробности, относящиеся к вашему делу. Я постараюсь сделать вещи проще:
Создание файлов четверок:
- index.php: тестовый файл.
- code.js: фактический код с функциями Ajax, getJS, getHTML
- content.php: любой файл PHP, который будет печатать чистый HTML без JS
- content.js: код JavaScript, который вы хотите динамически запускать.
index.php
<html>
<head>
<script src="code.js"></script>
</head>
<body>
<input type="button" onclick="Ajax('content.php', 'd_html');" value="Fill from content.php"/>
<div id="d_html"></div>
<br>
<input type="button" onclick="Ajax('content.js', 'd_js');" value="Fill from content.js"/>
<div id="d_js"></div>
</body>
</html>
content.php
<span>Hello, I am dynamic span came from content.php</span>
content.js
//Ana javascript code you want to run it by Ajax function should go inside this function
function executeJS(element){
element.innerHTML = "<span>Hello, I am dynamic span came from content.js</span>";
}
code.js
//This function responsible for doing the ajax request for any file that will return pure HTML.
function getHTML(url, element){
var i, xhr, activeXids = [
'MSXML2.XMLHTTP.3.0',
'MSXML2.XMLHTTP',
'Microsoft.XMLHTTP'
];
if (typeof XMLHttpRequest === "function") { // native XHR
xhr = new XMLHttpRequest();
} else { // IE before 7
for (i = 0; i < activeXids.length; i += 1) {
try {
xhr = new ActiveXObject(activeXids[i]);
break;
} catch (e) {}
}
}
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4) {
return false;
}
if (xhr.status !== 200) {
alert("Error, status code: " + xhr.status);
return false;
}
element.innerHTML += xhr.responseText;
};
xhr.open("GET", url, true);
xhr.send("");
}
//This function will load javascript file on-demand and call executeJS function inside that file.
function getJS(url, element, cb){
var newjs = document.createElement('script');
// IE
newjs.onreadystatechange = function () {
if (newjs.readyState === 'loaded' || newjs.readyState === 'complete') {
cb();
}
};
// others
newjs.onload = function () {
cb();
};
newjs.src = url;
element.appendChild(newjs);
}
//This is same as your function, but now can handle both PHP and JS files
function Ajax(url, id){
var element = document.getElementById(id),
regex = /\.js$/;
if(!element){
alert("Invalid ID");
return false;
}
if(regex.test(url)){ //If url ends with JS, load using getJS
getJS(url, element, function(){
executeJS(element);
});
} else {
getHTML(url, element);
}
}