8
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

広告タグを非同期で読み込みたい!jQuery.getScriptがウルトラ便利!

Last updated at Posted at 2016-05-06

広告を入れるたびにgoogle page speedなどで指摘されるrenderingブロックの警告は、悩みの種です。
ということで、タグを非同期で呼びたいんだけど、jsファイル読むだけじゃなくて、その後関数を実行するような広告タグに出会いました。
その時に使った jQuery.getScript をご紹介します。

通常はasync, deferで対応出来る

広告用のscriptタグなど、非同期で読み込みたい時、普通は下記のように、 asyncdefer 属性を付けて対応すると思います。これで、renderingブロックせず、documentの解析が終わったらscriptを読むようにしてくれます。

<script type="text/javascript" src="xxxx.js" async></script>

scriptを読み込み後、関数を実行したい時はjQuery.getScript

しかし、scriptを読み込んだ後に、関数を実行するようなタグも一部存在します。実際にもらったコードはこんな感じでした。

# 某AdNetwork担当者: 「下記をbodyの上に埋め込んでください」
<script type="text/javascript" src="xxxx.js"></script>
<script type="text/javascript">AAAAA.run()</script>

この場合、asyncなどで呼び出した場合、順番が保証されず、 AAA is not defined というエラーが出て、広告が表示されない場合が出てきます。
(deferだと一部ブラウザでは順番保証されてるっぽいけど)
そこで、 jQuery.getScript です

<script type="text/javascript">
jQuery.getScript("xxxx.js", function(){
  AAAAA.run()
});
</script>

これで、 xxxx.js が読み込まれた後に、関数が実行されることを保証できました。簡単♪

参考

jQuery getScript

8
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?