Search code examples
javascriptjqueryhtmlcssbranding

Is document write the preferred way to write html to a third party site for corporate branding?


I have an existing header and footer navigation that I would like to apply to third-party applications and sites on various platforms.

Ideally I would like to instruct vendors to add one script tag in HEAD of the document that then uses javascript to do the following:

  1. Add stylesheets to document head
  2. Add script tags before the closing body tag (jquery and other libraries and a app.js)
  3. The app.js will then rely on jQuery to load navigation html after the opening body tag and other dom manipulation (adding classes, removing elements, etc.)

I after reviewing this discussion - is document write the best solution in the initial script tag given to a third party?

Thank you.


Solution

  • You don't need to document.write(); in order to inject code into the head. If they embed your remote JavaScript file into their page, anywhere, you should be able to just append a script/style elements to the head.

     var myScript = document.createElement('script');
     myScript.setAttribute('src', '...');
     myScript.setAttribute('type', 'text/javascript');
     document.getElementsByTagName('head')[0].appendChild( myScript );
    

    If you look at the Google Analytics embed code, you'll see some similarities. It's short enough that you should be able to figure out what is going on:

    <script>
      (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
      (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
      m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
      })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
    
      ga('create', '...', 'auto');
      ga('send', 'pageview');
    
    </script>