$.Event is not a function error - javascript

I am creating an simple Javascript BOT.Its an simple js bookmarklet when clicked will create blogs in Blogger.com...I used Below code
var script = document.createElement('script');
script.src = 'http://jqueryjs.googlecode.com/files/jquery-1.2.6.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
document.getElementsByClassName('blogg-button GEE3RVNDMU')[0].click()
document.getElementById("newBlog-title").value ="hello blogger";
var node = document.getElementById("newBlog-address");
node.focus();
document.getElementById("newBlog-address").value ="hellosblogger";
setTimeout(function() {game();},1250);
function game()
{
var e = $.Event("keydown", { keyCode: 8});
$("body").trigger(e);
}
Everything works perfect,But atlast I need to simulate Any keypress Event...So i used that in function game , But I get $.Event is not a function error in Firexfox console . Please some one guide me or please tell any alternative to do an simple keypress event..It can be any key.

There really is no function named Event in the jquery library. To bind a event to jquery object, you can use Jquery.Bind which actually has the same syntax as the one you've used in your code.
So, to summarize:
$.bind("keydown",function(){})
For more info: http://api.jquery.com/bind/

See this link.
All works without errors.
Maybe you should use latest version of jQuery.
Code:
var script = document.createElement('script');
script.src = 'http://code.jquery.com/jquery-1.10.2.min.js';
script.type = 'text/javascript';
script.onload = game;
document.body.appendChild(script);
function game() {
console.log($("body"));
var e = $.Event("keydown", { keyCode: 8});
$("body").trigger(e);
}

Related

Load jQuery First After DOMContentLoaded

I am trying to load some scripts after DOMContentLoaded event and I am trying to use the following script for this. I'm not sure if the following is the best way to do this but I am having an issue with the following code because I need to load jquery first because my other scripts are depend on it. I have no idea how to do this any help would be greatly appreciated. Thank you very much.
<script>
document.addEventListener('DOMContentLoaded', function() {
var script = document.createElement('script');
script.src = 'https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.12.4.min.js';
document.getElementsByTagName('body')[0].appendChild(script);
var script1 = document.createElement('script');
script1.src = '/myscript1.js';
document.getElementsByTagName('body')[0].appendChild(script1);
var script2 = document.createElement('script');
script2.src = '/myscript2.js';
document.getElementsByTagName('body')[0].appendChild(script2);
});
</script>
Please know that dynamic scripts behave as async by default, which means that the script that loads first will also run first. So, the issue might be here that myscript1.js & myscript2.js are very small scripts and thus it loads and runs first before jquery script could load. To fix this you can pass script.async=false to each script so that script loads and run in the order they are being added to the document like:
document.addEventListener('DOMContentLoaded', function() {
var script = document.createElement('script');
script.src = 'https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.12.4.min.js';
script.async = false;
document.getElementsByTagName('body')[0].appendChild(script);
var script1 = document.createElement('script');
script1.src = '/myscript1.js';
script.async = false;
document.getElementsByTagName('body')[0].appendChild(script1);
var script2 = document.createElement('script');
script2.src = '/myscript2.js';
script.async = false;
document.getElementsByTagName('body')[0].appendChild(script2);
});
and if you want to keep things DRY (Don't repeat yourself), you can use a helper function like:
document.addEventListener('DOMContentLoaded', function() {
function loadScript(src) {
let script = document.createElement('script');
script.src = src;
script.async = false;
document.getElementsByTagName('body')[0].appendChild(script);
}
loadScript('https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.12.4.min.js');
loadScript('/myscript1.js');
loadScript('/myscript2.js');
});

'$ is not defined' on first load

I'm writing a html plugin for a tool(sonarqube).
In this I need to write code in below fashion by first registering a extension.
While running the code, I'm facing:
ReferenceError: $ is not defined
Code:
window.registerExtension('CustomPlugin/muPlugin', function (options) {
script = document.createElement('script');
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js';
document.head.appendChild(script);
var pluginContainer = document.createElement('div');
pluginContainer.setAttribute("id", "pluginContainer");
options.el.appendChild(pluginContainer)
$("#pluginContainer").load("/static/CustomPlugin/customPluginWebPage.html"); // Facing error on this line.
return function () {};
});
It works when I load the plugin second time, but not the first time.
Any suggestion, how can I make sure jquery is available the first time?
Thanks you
Possible duplication of - document.createElement(“script”) synchronously
ES5:
You can create your element with an "onload" handler, and that will be called when the script has been loaded and evaluated by the browser.
script = document.createElement('script');
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js';
//Bind a onload handler
script.onload = () => {
console.log($);
};
document.head.appendChild(script);
EDIT 1:
ES6:
The above is the best solution, unless you're prepared to host jQuery locally then you could use dynamic import() which runs asynchronously. Support is not great - https://caniuse.com/#feat=es6-module-dynamic-import. Here is another link making use of this. I would only recommend using this where BabelJS is used.
import('./jquery.min.js').then((jquery) => {
window.jQuery = jquery;
window.$ = jquery;
// The rest of your code
});
Try using setTimeOut()
window.registerExtension('CustomPlugin/muPlugin', function (options) {
script = document.createElement('script');
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js';
document.head.appendChild(script);
var pluginContainer = document.createElement('div');
pluginContainer.setAttribute("id", "pluginContainer");
options.el.appendChild(pluginContainer);
setTimeout(() => {
$("#pluginContainer").load("/static/CustomPlugin/customPluginWebPage.html");
}, 2000);
return function () {};
});

In JavaScript how to wait for dynamically injected scripts are loaded before start using them?

Without using any external library how can I wait for a script to load before using it.
In my case I'm loading the scripts using:
(function (w,d,t,s,e,r) {
e = d.createElement(o);
r = d.getElementsByTagName(o)[0];
e.async = 1;
e.src = g;
r.parentNode.insertBefore(e, r)
})(window, document, 'script', '//mydomain.com/path/to/script.js');
And later:
// then later I want to use some code form the script:
var obj = new classFromTheInjectedScript();
Is there away to wait for the script to load and then start using it?
Note: I have a way that I can trigger an event within the script I want
to load and then listen to it as you can see below, but is this a good idea?
(function(w,d){
document.addEventListener('scriptLoadedCustomEvent',onScriptReady);
function onScriptReady(){
// what I need to do goes here!
}
})(window,document);
You should be able to do something like this!
var script = document.createElement('script');
script.src = url; //source
var callback = function (){
// do stuff after loaded
}
script.onload = callback;
document.head.appendChild(script); //inject where you need it to be
You can use onload and onerror events for <script> tag. Good example here.
Here is a function that would be help to load a script and on successful load.. you can wait and perform your actions
function loadScript(url) {
const w = window;
const d = document;
const l = () => {
const s = d.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = url;
const x = d.getElementsByTagName('script')[0];
x.parentNode.insertBefore(s, x);
s.addEventListener('load', () => {
// This loads the script
yourFunctionAfterScriptLoaded();
});
};
if (w.attachEvent) {
w.attachEvent('onload', l);
} else {
w.addEventListener('load', l, false);
}
}
or you can directly use the script onload function as shown in this link
you could read the file source and inserting it in a script tag manually, so you will have the AJAX response event

load javascript files run-time

I have a script which load a javascript file run-time or async
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = 'file.js';
s.onreadystatechange = function(){
console.log(this.readyState)
};
s.onload = function(){
console.log('onload')
};
body.appendChild(s);
The problem is that when s.onload is triggered and onload is printed in the console the script isn't loaded completely and when calling a function from the file undefined is returned
If a setTimeout is setup after the script is onload it works, but that isn't good practice
Have made some research on the topic and found the onreadystatechange event.. But the event is never triggered in my code?!
How to add an event which is triggered when the script is completely loaded?
The order is important. Append the element first and add the src last:
var s = document.createElement('script');
s.type = 'text/javascript';
body.appendChild(s);
s.onreadystatechange = function(){
console.log(this.readyState)
};
s.onload = function(){
console.log('onload')
};
s.src = 'file.js';

Delay script loading

So if I have the following:
<script type="text/javascript" src="offsite file I am referencing"></script>
and I simply want to delay the execution of calling that file using settimeout, how would I go about that?
Very strange in that I would have no problem using settimeout on a simple function, but I am kind of stumped in this seemingly more simple situation.
My thought would be I could just make a function that calls that file after x amount of time, but calling the file in the function seems to be escaping me.
you are almost there.
in your settimeout callback function do the following:
var script = document.createElement('script');
script.src = "http://whatever.com/the/script.js";
document.getElementsByTagName('head')[0].appendChild(script);
The simplest way would be to let the script file load normally and just call a main function in it with setTimeout() like this:
<script type="text/javascript" src="offsite file I am referencing"></script>
<script type="text/javascript">
setTimeout(executeMainFunction, 5000); // function in offsite js file
</script>
If you cannot do that for some reason, then you can delay the loading of the external script file like this:
setTimeout(function() {
var headID = document.getElementsByTagName("head")[0];
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = 'http://www.somedomain.com/somescript.js';
headID.appendChild(newScript);
}, 5000);
Here's a reference article on dynamic loading of script files (and other types of resources): http://www.hunlock.com/blogs/Howto_Dynamically_Insert_Javascript_And_CSS.
You can use DOM manipulation to create a new script tag at runtime. Adding it into the document will load the external JS file just as if you had written it into the HTML in the first place.
var loadScript = function(sourceSrc){
var scriptTag = document.createElement('script');
scriptTag.src = scriptSrc;
document.getElementsByTagName('head')[0].appendChild(scriptTag);
}
You can delay the script from loading, until the page finishes loading, using the HTML script defer attribute:
<script src="offsite file I am referencing" defer></script>
If the purpose of this exercise is to delay the loading of external resources to simulate potential real life scenarios (e.g. when loading 3rd party widgets, etc), then I'd go down a very different route.
The following are two different delay proxy implementations that can be used to simulate and test unexpected network conditions:
http://www.deelay.me/
https://www.npmjs.com/package/grunt-connect-delay
They both work by using a prefix like /delay/5000/ to specify the delay simulation period.
Mozilla Developer Network explains various approaches:
MDN Async Script Techniques
<script async src="file.js"></script>
or
var script = document.createElement('script');
script.src = "file.js";
document.body.appendChild(script);
or if your JavaScript is in a String:
var blob = new Blob([codeString]);
var script = document.createElement('script');
var url = URL.createObjectURL(blob);
script.onload = script.onerror = function() { URL.revokeObjectURL(url); };
script.src = url;
document.body.appendChild(script);
There is also good information when async is not async as well as how to get around those cases.
I have created for ReactJS and its worked for me.
1. File: widget.js with promise:
const delayTime = 20000; // loading 20sec delay.
const loadJS = async () => {
return await new Promise(function (resolve, reject) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.src = 'https://yoururl.com/js/widget.js';
script.onload = resolve;
script.onerror = () => {
reject('Cannot load js')
document.head.removeChild(script);
}
document.head.appendChild(script);
}) }
function initLoadJS() {
loadJS()
.then(()=> console.log('testing'))
.catch((error)=>console.error(error)) }
function delayLoadingJS() {
setTimeout((event)=>initLoadJS(event), delayTime);
}
export default delayLoadingJS;
2. Calling delayLoadingJS() function on the page:
When page loading completed then after 20 sec later initLoadJS() method will trigger and it attach the 3rd party javascript file(https://yoururl.com/js/widget.js) on page.
componentDidUpdate(prevProps, prevState) {
if (this.state.page !== prevState.page) {
delayLoadingJS();
}
}
For a NextJS cript, the code below will work fine:
<script id="sample_id">
setTimeout(function(){
var script = document.createElement('script');
script.src = "https://link_to_load";
document.getElementsByTagName('head')[0].appendChild(script);
},
4000);
</script>

Categories

Resources