Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 757
JMW Avatar asked Mar 05 '26 10:03

JMW


1 Answers

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()?

like image 100
Teemu Avatar answered Mar 07 '26 22:03

Teemu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!