Vlad Holubiev
Vlad Holubiev

Reputation: 5154

jQuery doesn't run after including it to a page

Something strange happening with my Chrome's console! The task is to add jQuery lib to a page and then do some stuff using it (jQuery). I wrote some code:

    //First part   
    var script = document.createElement('script');
    script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js';
    script.type = 'text/javascript';
    document.getElementsByTagName('head')[0].appendChild(script);
    //Second part 
    $('a[href="?tab=MM"]').text('asdasdasd');

When I paste whole code to console - I get TypeError: Property 'text' of object [object HTMLAnchorElement] is not a function

BUT! When I paste separately first part(which creates script-tag) and then second (jQuery expression) I get normal expected result!

Can anyone explain what I do wrong? And what should I do to make script in a right way?

Upvotes: 0

Views: 76

Answers (1)

Quentin
Quentin

Reputation: 943651

When you run the code line by line, the browser has time to download and execute the JavaScript in the script element you are appending.

When you include it in the page, the "Second part" is executed as soon as the script element is added to the DOM but the JS that adds to the page won't be executed until the current script is finished.

This is why jQuery's getScript method takes a callback function.

You can get a similar effect but wrapping your "second part" in a function and using that as a load event listener on the script element. I don't know what browser support for that is like though.

Upvotes: 5

Related Questions