JMW
JMW

Reputation: 7807

How can I include a script with document.write?

We need to add a script to our web application. It basically adds an corporate menu.

So we've received a script to include in the body of our web application:

<!-- BEGIN NAVIGATION -->
<script type="text/javascript" src="https://intranet.local/?getCorporateJsMenu"></script>
<!-- END NAVIGATION -->

And the content of https://intranet.local/?getCorporateJsMenu basically looks like this:

document.write('<script type="text/javascript" src="..."></script>');
//....
document.write('<div>');
document.write('<ul>');
//...
document.write('<li><a href="...">...</a></li>');
//...
document.write('</ul>');
document.write('</div>');

After having placed the <!--NAVIGATION--><script... directly into the HTML body, we were experiencing severe page load performance problems.

So our idea was to add the menu with JavaScript, when everything has already been loaded with something like this:

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://intranet.local/?getCorporateJsMenu';
var domparent = jQuery('#header').get();
domparent[0].appendChild(script);

With Firebug we see, that the script element has been added to the HTML content and the script has been loaded from the network, but somehow the document.write of the loaded script doesn't get executed. Why?


We cannot modify the contents of https://intranet.local/?getCorporateJsMenu since it comes from third party.

Upvotes: 2

Views: 31280

Answers (3)

Robert Hoffmann
Robert Hoffmann

Reputation: 2416

Try this:

document.write('<scr' + 'ipt type="text/javascript" src="..."></scr' + 'ipt>');

Upvotes: 2

Teemu
Teemu

Reputation: 23396

This happens because the script execution stops at the first found literal </script> tag, no matter if it was enclosed in the parenthesis. You need to obfuscate the ending script tag, for example:

document.write('<script type="text/javascript" src="..."><\/script>');

However, it seems you use also jQuery. Why not use the jQuery methods to load a script and add the content to a page rather than document.write()?

Upvotes: 14

dandavis
dandavis

Reputation: 16726

Here is an example of hijacking document.write() to bring 21st century loading performance to legacy scripts:

<script>
    var writes = [];
    document.write = [].push.bind(writes);
</script>

<div id=targ></div>

<script type="text/javascript" src="https://intranet.local/?getCorporateJsMenu"></script>
<script>
    document.getElementById("targ").innerHTML = writes.join(" ");
</script>

I've used the patterns to support ads on a SPA site, as well as to cache embeds, and in one case to modify the content's style before injecting.

Upvotes: 4

Related Questions