tsds
tsds

Reputation: 9010

Loading external js in IE

I want to load external javascript file but I can't use AJAX requests because of same origin policy, and I have a code:

<script type="text/javascript">
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = 'test.js';
    head.appendChild(script);
</script>

That is ok everywhere (Firefox, Chrome, Opera, IE9, IE6) but not in IE8, IE7.
How can I make it work in IE8?

Upvotes: 0

Views: 3583

Answers (3)

DanielB
DanielB

Reputation: 20220

How about the old document.write('<script language="javascript" src="test.js"><\/script>'). Also you do not have to append to head you can use body to.

Upvotes: 1

tmont
tmont

Reputation: 2620

I'm not sure why you had problems in IE, but the following worked in Firefox 4, IE6 and IE9 (i.e. the browsers I had available):

<html>
<head>

</head>
<body>
    <script type="text/javascript">
        var head = document.getElementsByTagName('head')[0];
        var script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js';
        head.appendChild(script);

        var interval = window.setInterval(function() {
            if (typeof($) !== "undefined") {
                $("<p>it worked!</p>").appendTo(document.body);
                window.clearInterval(interval);
            }
        }, 100);
    </script>

</body>
</html>

Upvotes: 1

Nathan
Nathan

Reputation: 6216

Try reading up about JsonP :)

Upvotes: 1

Related Questions