How to run inline script AFTER jquery confirmed as defined

inline event handler javascript
javascript execute after all scripts loaded
listener approach in javascript
addeventlistener
call javascript function after page load complete
jquery run script after everything loaded
run javascript after page load
javascript before page load event

I'm working under particular circumstances and I am trying to get a slick slider carousel to run.

I get an error that $ is not defined.

Unless I use

window.onload = function(e){
  $(document).ready(function () {
    $('.js-slick').slick({
      autoplay: true,
      autoplaySpeed: 5000,
      dots: true,
      fade: true,
      speed: 1000
    });
  });
};

The problem is, this slider is the first thing on the page, so I can not wait until everything is loaded, as it takes way too long.

I cannot change the order of my script tag or make sure the jQuery link is properly placed in the head an so on.

I know that other sliders on the page work just fine, and I also know that this particular one works fine once the proper files are loaded

There must be a way to check if $ is defined, keep checking until it is, and then run the script once confirmed.

var timer = setInterval(checkjQuery, 5000);

function checkjQuery() {
  if(window.jQuery) {
    clearInterval(timer);
    callSlick();
    console.log('jQuery is loaded');
    return;
  } else {
    console.log('waiting');
  }
}

function callSlick() {
  $('.js-slick').slick({
      autoplay: true,
      autoplaySpeed: 5000,
      dots: true,
      fade: true,
      speed: 1000
    });
};

Similar to DanDavis solution

How to make script execution wait until jquery is loaded, I see you use text/Scripts , which is not the right mimetype for javascript. Use this: Also you read somewhere it's good to inline small Javascript, so imagine you need jQuery in a page, baboom, $ is not defined (.. yet ^^). I love the And add at the bottom of your layout, after jQuery include if (window. A lightweight and easy-to-use jQuery plugin which allows apply inline confirmation actions to any elements without messing with confirm dialogs. How to use it: 1. To use this plugin, you have to load the JavaScript file jquery.inline-confirmation.js after jQuery library.

use a waiter:

setTimeout(function wait(){
 if(!window.$) return setTimeout(wait, 100);

 // do stuff needing $ here:
 console.info("$=", $);
}, 100);

$ is not a function but jQuery is loaded when adding JavaScript to a , The Drupal js documentation states. Note: Since Drupal uses jQuery.noConflict() and only loads JavaScript files when required, to use jQuery  The confirm alert in JavaScript A confirm alert is a type of alert box where a user is asked before taking a certain action. A simple JavaScript confirm dialogue can be created by using the following code: [crayon-5e9f00bb2ab3b986440312/] The user is presented with the Ok and cancel buttons. For each action, you can perform …

IMO the answer from @dandavis solves the issue the simplest.

I'd like to offer a way to make a simple "wait-er" re-usable and show how to integrate this with the code you shared.

A re-usable wait-er:

function waitUntil(getResource, callback) {
  // Copied from @dandavis' answer
  setTimeout(function wait() {
    const resource = getResource();
    if(!resource) return setTimeout(wait, 100);

    callback(resource);
  }, 100);
}

window.onload = function(e) {
  waitUntil(function () { return window.$; }, function () {
    $(document).ready(function () {
      $('.js-slick').slick({
        autoplay: true,
        autoplaySpeed: 5000,
        dots: true,
        fade: true,
        speed: 1000
      });
    });
  });
};

Or if you wanted to, you could make it promise-based:

function waitUntil(getResource) {
  return new Promise((resolve, reject) => {
    setTimeout(function wait() {
      const resource = getResource();
      if(!resource) return setTimeout(wait, 100);

      resolve(resource);
    }, 100);
  });
}

window.onload = function(e) {
  waitUntil(function () { return window.$; })
    .then(function () {
      $(document).ready(function () {
        $('.js-slick').slick({
          autoplay: true,
          autoplaySpeed: 5000,
          dots: true,
          fade: true,
          speed: 1000
        });
      });
    });
};

Working with Inline Event Handlers, We've all heard the reasons that you should NEVER - and I mean NEVER - use them. Now, I'm not here to tell you to start using inline event handlers in your Web and remove inline event handlers using jQuery-assisted JavaScript. I was skeptical at first, but one look at the source code confirmed it. To include a JavaScript function, it is as simple as include a <script> tag and define the function inside the script block. Now, to call the function, add an onclick event on the employee name hyperlink and call the function. The below code does that.

Running Your JavaScript at the Right Time, Run your code at the right time by making sense of DOMContentLoaded, load, you want to ensure your code runs only after your DOM has been fully loaded. To review, a simple script element can be some code stuck inline somewhere: Scripts marked with defer run in the order in which they were defined, but they  Disable inline JavaScript for security Use JS to JS template engine in Express to ban all inlined JavaScript. The source code for this blog post is in bahmutov/disable-inline-javascript-tutorial and the demo showing the insecure page that allows inline JavaScript tags is at insecure demo .

Stop paying your jQuery tax, You need a “stable” DOM while executing a script. In the screenshot below you can see how it took 150ms just to confirm we have the right version of jQuery. If you decide to render CSS inline you may avoid this, but in turn have a Just after we load jQuery we can pass all the functions we captured to  Asynchronous means the rest of the code is executed, and so your document-ready handler (DRH) line is running before jQuery is present in the environment. Here's a really hacky way of resolving this. It involves making a temporary substitute of jQuery whose job is just to log the DRH callbacks until jQuery has arrived.

Confirm box in javascript with yes no option, Net, jQuery, jQuery Plugins Confirmation Dialog Box. 66 comments. use a confirm() box At first I simply used the JavaScript alert and After JOptionPane. 2017 Avoid inline JavaScript - changing the behaviour would mean editing every  In JavaScript / jQuery we can define a function in several ways. We can also create a user defined function just like other jQuery functions for DOM elements. In this article I will explain some methods to declare a function and also explain how to create a user defined function.

Comments
  • I've tried this multiple times and it still does not seem work. It is already referenced far earlier in the head tag anyway, thanks for the reply
  • What bothers me is the "I cannot change the order of my script tag or make sure the jQuery link is properly placed in the head an so on" part. Why? You clearly can change something. Order is crucial in JS. If you're loading your code using a <script> tag than have you tried to add the defer attribute? Such will make sure your script is executed once the DOM is parsed. Using an aggressive interval/loop would be odd...
  • You could explain a bit better the following: Does the slider already uses jQuery? Where is it placed? Where is jQuery placed? Why your script tags are not right before the closing </body> tag but rather in a render-blocking manner - in the head of your document? Do you have control over the hosting page or you have an XY problem?
  • @RokoC.Buljan Yes, I've tried the defer attribute. I'm forced to edit the source code of a text widget of an uncommon cms. This places the code at the bottom of a rather long page. I'm not sure why I can't just reference jquery just before, I think I'm doing something wrong. The slider does use jquery and it's all placed in the head, which I don't have access to
  • Just wondering if your jQuery goes in compatibility mode (works wordpress pages when you need an inline code)? If so, you can try to wrap the statement jQuery(document).ready(function( $ ) { // your code });
  • out of curiosity, what happens on the page if the net hiccups and jquery doesn't load? Does it freeze the browser up due to the looping?