开发者

IE7 appends but doesn't load <script> when injected

I have a JS that lives before closing </body> tag that contains a method that injects another <script> element to load a JS file if a certain action is performed.

The code snippet for th开发者_StackOverflow中文版e append looks something like this:

var script = document.createElement('script');

script.setAttribute('type', 'text/javascript');
script.setAttribute('src', 'http://path/to/script.js');

document.body.appendChild(script);

That code works fine on all browsers except for IE7. On IE7, it successfully appends the script into the DOM, but does not load it.

Another thing that I'd like to point out is that I have also tried to append that script to <head> and it still doesn't work.


Instead of adding your script element to the body element (which is not closed when you try to do that just before the closing </body> tag), try to add your script to the head. Moreover, don't use setAttribute, but set properties of the new DOMElement directly:

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://path/to/script.js';
document.getElementsByTagName('head')[0].appendChild(script);


Add the script after the DOM has finished loading? I know IE6 has problems with modifying the DOM before it has been loaded (Will fatal with: Can not load this page).

Either use window.onload or just put the script in a javascript file that you include in the header.

Also, in case the JavaScript resource is not actually a JavaScript file but some script that generates a JavaScript file make sure you're sending the JavaScript content header.


Have you tried appending the script tag and then setting the source? I know IE7 requires this order when appending style tags so it might be worth a shot!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜