Search code examples
javascriptdocument.write

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.


Solution

  • 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.