Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
258 views
in Technique[技术] by (71.8m points)

javascript - Dynamically added script will not execute

I am dynamically adding a script of a github gist. If I added it to the html before the page loads, the script will execute. But If I try to add it to the page after it loads it adds the script to the page but doesn't execute it.

Here is how I am adding it to the page

Html

<div id="results"></div>

Javascript

$('#results').click(function() {
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = "https://gist.github.com/1265374.js?file=GetGists.js";
    document.getElementById('results').appendChild(script);
    console.log('script added');
});

Here is the live example

http://jsfiddle.net/guanome/JqB3g/3/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

So, the best option I can see is to override (even if just temporarily while the script loads) document.write. It is sort of a work around, but since you don't control the code coming in, I think it may be the best you've got. You also shouldn't be using document.write anytime after the page loads, but just in case, I'd maybe comb through your code.

Here's a fiddle with a working solution. If you wanted to revert document.write after the script loaded, you can always check to see if script.complete is true, otherwise, listen for an onload event, which should allow you to change document.write back. I'm too lazy to code it into the fiddle at the moment, but this would be the code generally:

script.src = "...";
document.getElementById("results").appendChild(script);
if(script.complete) document.write = document._write;
else script.load(function() { 
    // Goes to the end of the run queue so that the script 
    // is guaranteed to run before this code
    setTimeout(function(){document.write = document._write;},0);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...