Budowniczowie

Konstruktory to standardowy sposób tworzenia elementów w skryptach Google Ads. Dzięki nim możesz tworzyć elementy Google Ads w sposób synchroniczny lub asynchroniczny. Możesz też sprawdzić, czy operacja się powiodła, i podjąć odpowiednie działania w zależności od jej wyniku. Ten fragment kodu pokazuje, jak utworzyć słowo kluczowe za pomocą kreatora.

// Retrieve your ad group.
let adGroup = AdsApp.adGroups().get().next();

// Create a keyword operation.
let keywordOperation = adGroup.newKeywordBuilder()
    .withCpc(1.2)
    .withText("shoes")
    .withFinalUrl("http://www.example.com/shoes")
    .build();

// Optional: examine the outcome. The call to isSuccessful()
// will block until the operation completes.
if (keywordOperation.isSuccessful()) {
  // Get the result.
  let keyword = keywordOperation.getResult();
} else {
  // Handle the errors.
  let errors = keywordOperation.getErrors();
}

Każdy typ obiektu, który można utworzyć za pomocą skryptów Google Ads, jest tworzony za pomocą tego wzorca kreatora.

Możliwe spowolnienie działania witryny

Domyślnie skrypty Google Ads wykonują operacje asynchronicznie. Dzięki temu skrypty mogą grupować operacje w partie i osiągać wysoką wydajność. Jednak wywołanie metod Operation, takich jak isSuccessful() i getResult(), powoduje, że skrypty Google Ads muszą opróżnić listę oczekujących operacji, co może prowadzić do pogorszenia wydajności. Zamiast tego utwórz tablicę, która będzie przechowywać operacje, a potem przejdź przez tę tablicę, aby pobrać wyniki.

Słaba wydajność Dobra wydajność
for (let i = 0; i < keywords.length; i++)
  let keywordOperation = adGroup
    .newKeywordBuilder()
    .withText(keywords[i])
    .build();

  // Bad: retrieving the result in the same
  // loop that creates the operation
  // leads to poor performance.
  let newKeyword =
      keywordOperation.getResult();
  newKeyword.applyLabel("New keywords);
}
// Create an array to hold the operations
let operations = [];

for (let i = 0; i < keywords.length; i++) {
  let keywordOperation = adGroup
    .newKeywordBuilder()
    .withText(keywords[i])
    .build();
  operations.push(keywordOperation);
}

// Process the operations separately. Allows
// Google Ads scripts to group operations into
// batches.
for (let i = 0; i < operations.length; i++) {
  let newKeyword = operations[i].getResult();
  newKeyword.applyLabel("New keywords);
}