Static GitHub Issues

[1330] [question] in a plugin, how to add js text first then include js file

prev: CSS classes order changes when generating site
next: Issue with single file components and css loader

I am writing a nuxt plugin for piwik and can't get the plugin to work in the way I think would be best.

The default example code to include Piwik on your webpage is as follows:

<!-- Piwik -->
<script type="text/javascript">
  var _paq = _paq || [];
  /* tracker methods like "setCustomDimension" should be called before "trackPageView" */
  _paq.push(['trackPageView']);
  _paq.push(['enableLinkTracking']);
  (function() {
    var u="//piwik.example.com/";
    _paq.push(['setTrackerUrl', u+'piwik.php']);
    _paq.push(['setSiteId', '1']);
    var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
    g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s);
  })();
</script>
<!-- End Piwik Code -->

So you have to set setTrackerUrl and setSiteId before loading the piwik.js file. If you do this in plugin.js it works fine, but I think it would be cleaner to do this in index.js to avoid adding js src files during runtime. Unfortunately I am unable to make sure that after rendering the code is still loaded in this order.

What I tried:

  • call this.options.head.script.push in index.js, one time to add the _paq.push's with innerHTML and one time to add the src to piwik.js.
  let config_js = '_paq.push(["setTrackerUrl", "' + (options.trackerUrl || options.piwikUrl+'piwik.php') + '"]);'
  config_js += '_paq.push(["setSiteId", "' + options.siteId + '"])'
  this.options.head.script.push({ 
    innerHTML: config_js, type: 'text/javascript'
  })
  this.options.head.script.push({
    src: options.scriptUrl || options.piwikUrl+'piwik.js',
    async: true,
    defer: true
  })

This doesnt work because using innerHTML encodes double & single quotes to htmlentities and afaik you can only disable encoding with vue-meta for the whole script group (and maybe interfering with other plugins)

<script data-n-head="true" type="text/javascript">_paq.push([&quot;setTrackerUrl&quot;, &quot;//piwik.example.com/piwik.php&quot;]);_paq.push([&quot;setSiteId&quot;, &quot;1&quot;])</script>
  • set _paq.push's at beginning of plugin.js and add piwik.js deferred in index.js with this.options.head.script.push({ defer: true }). This doesnt work because the script tag for piwik.js will have a defer tag but is not added at the bottom of the document (e.g. after window. NUXT) while the _paq.push's are in /_nuxt/app.js at the very bottom of the page.

Are there any other possibilities to keep the javascript in the required order that I havent thought of?

<!--cmty--><!--cmty_prevent_hook--><div align="right"><sub><em>This question is available on <a href="https://nuxtjs.cmty.io">Nuxt.js</a> community (<a href="https://nuxtjs.cmty.io/nuxt/nuxt.js/issues/c1179">#c1179</a>)</em></sub></div>