D
D
Danil Trubitsyn2017-08-19 07:20:22
JavaScript
Danil Trubitsyn, 2017-08-19 07:20:22

How to make an external script load lazy in Wordpress?

Online chat scripts for a site from Bitrix24 or from Vkontakte are loaded with a long TTFB.
I've tried everything, I can't set it up so that they are loaded after the site page is fully loaded. For LPTracker, this works fine, but on the developer's side.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Danil Trubitsyn, 2017-08-19
@ali3412

This is what worked for me

<script>
var scripts = new Array('путь/до/файла.js');
  var css = new Array('путь/до/styles.css');

  function downloadJSAtOnload() {
    var element;
    for(var i = 0; i < scripts.length; i++){
      element = document.createElement("script");
      element.src = scripts[i];
      element.type = 'text/javascript';
      document.body.appendChild(element);
    }
    for(var i = 0; i < css.length; i++){
      element = document.createElement("link");
      element.href = css[i];
      element.type = 'text/css';
      element.rel = 'stylesheet';
      document.body.appendChild(element);
    }
  }
  if (window.addEventListener)
    window.addEventListener("load", downloadJSAtOnload, false);
  else if (window.attachEvent)
    window.attachEvent("onload", downloadJSAtOnload);
  else window.onload = downloadJSAtOnload; 
</script>

M
Mikhail Lisetsky, 2017-08-19
@MacKor

wp_enqueue_script('newscript', '//js/custom_script.js', array(), '1.0.0', true);

Isn't it the same? Include the script before the closing body.

A
Alexander Pushkarev, 2017-08-19
@AXP-dev

After the page loads, create a script tag and load it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question