<button id="server">Server play</button>
<script>
var start = {
get: function (id) {
return document.getElementById(id);
},
setup: function () {
this.get('server').onclick = this.remoteRequest;
},
remoteRequest: function () {
var script = document.createElement("script");
script.src = "server.js?callback=passObj";
document.body.appendChild(script);
},
};
var passObj = {
serverPlay: function (data) {
console.log(data.foo);
},
num: 10
}
start.setup();
</script>
//server.js
passObj.serverPlay({"foo": 'bar'});
frame通常使用的情况
<script>
元素无阻塞地下载 var script = document.createElement("script");
script.src = "later.js";
document.documentElement.firstChild.appendChild(script);
//mian.js
var mynamespace = {
inline_scripts: []
}
//内敛脚本
mynamespace.inline_scripts.push(function() {
console.log(a);
});
//later.js
var a = 10;
(function() {
var i, scripts = mynamespace.inline_scripts, max = scripts.length;
for(i = 0; i < max; i++) {
scripts[i]();
}
})();
//main.js
document.getElementById("server").onclick = function() {
require('later.js', function() {
alertFunc();
});
}
function require(file, cb) {
var script = document.getElementsByTagName('script')[0];
var newjs = document.createElement('script');
//ie
newjs.onreadystatechange = function() {
if(newjs.readyState == 'loaded' || newjs.readyState === 'complete') {
newjs.onreadystatechange = null;
cb();
}
}
//other
newjs.onload = function() {
cb();
}
newjs.src = file;
script.parentNode.insertBefore(newjs, script);
}
//later.js
var alertFunc = function() {
alert(0);
}
//main.js
var preload;
if(/*@cc_on!@*/false) { //使用条件注释的IE嗅探
preload = function(file) {
new Image().src = file;
}
} else {
preload = function(file) {
var obj = document.createElement('object');
var body = document.body;
obj.width = 0;
obj.height = 0;
obj.data = file;
body.appendChild(obj);
}
}
preload('later.html');
//later.html
<script type="text/javascript">
alert(0);
</script>