0

I need to create a script element and append the google map function there. I'm wondering: can I use a variable in my function via the append.

var center = {lat: -34.397, lng: 150.644};

document.createElement("script").append(
      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          center: center,
          zoom: 8
        });
      }
);
1
  • Why not create a separate javascript-file with function that accepts the coordinates as a parameter and reference that in your page. Commented Aug 31, 2018 at 10:24

2 Answers 2

2

You can run script using this method. Because append only used for Node-s.

function runScript(func) {
    var e = document.createElement('script');
    e.innerHtml = func.toString();
    document.head.appendChild(e);
}

runScript(function(){
    alert('okay');
});

You can run any js script using this method.

runScript(function(){
    map = new google.maps.Map(document.getElementById('map'), {
      center: center,
      zoom: 8
    });
});
Sign up to request clarification or add additional context in comments.

Comments

1

.append(...) is only for a Node or a DOM string. Not for JS code. https://developer.mozilla.org/en-US/docs/Web/API/ParentNode/append

Why aren't you calling initMap() directly? Like this:

var center = {lat: -34.397, lng: 150.644};

function initMap() {
  return new google.maps.Map(document.getElementById('map'), {
    center: center,
    zoom: 8
 });
 
 var map = initMap();

1 Comment

This is used in a separate file without Google API. The function of google is not defined. I'm trying to create a function through the append, to run it already on the page.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.