user2916134
user2916134

Reputation:

JavaScript - Dynamic Script tag causing "unexpected token illegal"

I'm getting an error dynamically generating this script tag. It doesn't seem to like the opening bracket. Can anyone help?

$(document).ready(function(){

  (function(callback){
    var s = document.createElement('script');
    s.setAttribute('type', 'application/ld+json');

    s.text = '{
      "@@context": "http://schema.org",
      "@@type": "Person",
      "name": "John Doe",
      "jobTitle": "Graduate research assistant",
      "affiliation": "University of Dreams",
      "additionalName": "Johnny",
      "url": "http://www.example.com",
      "address": {
        "@@type": "PostalAddress",
        "streetAddress": "1234 Peach Drive",
        "addressLocality": "Wonderland",
        "addressRegion": "Georgia"
      }
    }';
    s.onload = callback;
    document.body.appendChild(s);
  })();

})



</script>

Upvotes: 1

Views: 523

Answers (1)

Jacob
Jacob

Reputation: 78840

JavaScript does not allow multi-line string literals, so the s.text = ' lines are invalid syntax.

If you output pure JSON to your script instead, then you can do this to make it into a string:

s.text = JSON.stringify({
  "@@context": "http://schema.org",
  "@@type": "Person",
  "name": "John Doe",
  "jobTitle": "Graduate research assistant",
  "affiliation": "University of Dreams",
  "additionalName": "Johnny",
  "url": "http://www.example.com",
  "address": {
    "@@type": "PostalAddress",
    "streetAddress": "1234 Peach Drive",
    "addressLocality": "Wonderland",
    "addressRegion": "Georgia"
  }
});

Upvotes: 4

Related Questions