jQuery plugin file including the jQuery library - javascript

Ideally I'd like the js file containing the plugin also look after including the jquery library.
I've played with a couple of mechanisms without success, XHR script injection and basic script injection like:
myplugin.js:
var scriptElem = document.createElement('script');
scriptElem.src = 'jquery-1.6.1.js';
document.getElementsByTagName('head')[0].appendChild(scriptElem);
(function() {
jQuery.fn.myplugin = function() {
...
}
})();
but of course jQuery won't be defined in time.
Any suggestions?

I'm not sure if this is the best practice, I would personally leave the jQuery include up to the developer using my plugin.
But if you insist... :)
You should use 2 files, one would be your plugin, the other would be just a loader:
myplugin_loader.js
var scriptElem;
if(!window.jQuery){
// Include jQuery if it's not already loaded
scriptElem = document.createElement('script');
scriptElem.src = 'jquery-1.6.1.js';
scriptElem.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(scriptElem);
}
// Include the main plugin after jQuery
scriptElem = document.createElement('script');
scriptElem.src = 'myplugin.js';
scriptElem.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(scriptElem);
myplugin.js
(function() {
jQuery.fn.myplugin = function() {
...
}
})();
If jQuery is surely loaded, you can use myplugin.js, if in doubt, include myplugin_loader.js. Although as I said I would recommend against it.

you should not include jquery in your plugin jQuery is a requirement or dependency to use the plugin. You should Never include it in your plugin ! If you included it this would force the user to use a specific version of jquery and may even cause problems .

Copy the jquery library into the top of the same file as the plug-in?
Note that if you took this (not recommended approach), you should use noConflict and assign some personal variable to the jquery reference eg.
var $myjQuery = jQuery.noConflict();
and use this reference in your plugin instead of just $ or jQuery

Related

Injecting HTML and Scripts into a <div> element via jquery [duplicate]

Any idea why the piece of code below does not add the script element to the DOM?
var code = "<script></script>";
$("#someElement").append(code);
The Good News is:
It's 100% working.
Just add something inside the script tag such as alert('voila!');. The right question you might want to ask perhaps, "Why didn't I see it in the DOM?".
Karl Swedberg has made a nice explanation to visitor's comment in jQuery API site. I don't want to repeat all his words, you can read directly there here (I found it hard to navigate through the comments there).
All of jQuery's insertion methods use
a domManip function internally to
clean/process elements before and
after they are inserted into the DOM.
One of the things the domManip
function does is pull out any script
elements about to be inserted and run
them through an "evalScript routine"
rather than inject them with the rest
of the DOM fragment. It inserts the
scripts separately, evaluates them,
and then removes them from the DOM.
I believe that one of the reasons jQuery
does this is to avoid "Permission
Denied" errors that can occur in
Internet Explorer when inserting
scripts under certain circumstances.
It also avoids repeatedly
inserting/evaluating the same script
(which could potentially cause
problems) if it is within a containing
element that you are inserting and
then moving around the DOM.
The next thing is, I'll summarize what's the bad news by using .append() function to add a script.
And The Bad News is..
You can't debug your code.
I'm not joking, even if you add debugger; keyword between the line you want to set as breakpoint, you'll be end up getting only the call stack of the object without seeing the breakpoint on the source code, (not to mention that this keyword only works in webkit browser, all other major browsers seems to omit this keyword).
If you fully understand what your code does, than this will be a minor drawback. But if you don't, you will end up adding a debugger; keyword all over the place just to find out what's wrong with your (or my) code. Anyway, there's an alternative, don't forget that javascript can natively manipulate HTML DOM.
Workaround.
Use javascript (not jQuery) to manipulate HTML DOM
If you don't want to lose debugging capability, than you can use javascript native HTML DOM manipulation. Consider this example:
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "path/to/your/javascript.js"; // use this for linked script
script.text = "alert('voila!');" // use this for inline script
document.body.appendChild(script);
There it is, just like the old days isn't it. And don't forget to clean things up whether in the DOM or in the memory for all object that's referenced and not needed anymore to prevent memory leaks. You can consider this code to clean things up:
document.body.removechild(document.body.lastChild);
delete UnusedReferencedObjects; // replace UnusedReferencedObject with any object you created in the script you load.
The drawback from this workaround is that you may accidentally add a duplicate script, and that's bad. From here you can slightly mimic .append() function by adding an object verification before adding, and removing the script from the DOM right after it was added. Consider this example:
function AddScript(url, object){
if (object != null){
// add script
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "path/to/your/javascript.js";
document.body.appendChild(script);
// remove from the dom
document.body.removeChild(document.body.lastChild);
return true;
} else {
return false;
};
};
function DeleteObject(UnusedReferencedObjects) {
delete UnusedReferencedObjects;
}
This way, you can add script with debugging capability while safe from script duplicity. This is just a prototype, you can expand for whatever you want it to be. I have been using this approach and quite satisfied with this. Sure enough I will never use jQuery .append() to add a script.
I've seen issues where some browsers don't respect some changes when you do them directly (by which I mean creating the HTML from text like you're trying with the script tag), but when you do them with built-in commands things go better. Try this:
var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.src = url;
$("#someElement").append( script );
From: JSON for jQuery
It is possible to dynamically load a JavaScript file using the jQuery function getScript
$.getScript('http://www.whatever.com/shareprice/shareprice.js', function() {
Display.sharePrice();
});
Now the external script will be called, and if it cannot be loaded it will gracefully degrade.
What do you mean "not working"?
jQuery detects that you're trying to create a SCRIPT element and will automatically run the contents of the element within the global context. Are you telling me that this doesn't work for you? -
$('#someElement').append('<script>alert("WORKING");</script>');
Edit: If you're not seeing the SCRIPT element in the DOM (in Firebug for example) after you run the command that's because jQuery, like I said, will run the code and then will delete the SCRIPT element - I believe that SCRIPT elements are always appended to the body... but anyway - placement has absolutely no bearing on code execution in this situation.
This works:
$('body').append($("<script>alert('Hi!');<\/script>")[0]);
It seems like jQuery is doing something clever with scripts so you need to append the html element rather than jQuery object.
Try this may be helpful:
var fileref=document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src","scriptAnalytics.js");
document.getElementsByTagName("head")[0].appendChild(fileref);
I want to do the same thing but to append a script tag in other frame!
var url = 'library.js';
var script = window.parent.frames[1].document.createElement('script' );
script.type = 'text/javascript';
script.src = url;
$('head',window.parent.frames[1].document).append(script);
<script>
...
...jQuery("<script></script>")...
...
</script>
The </script> within the string literal terminates the entire script, to avoid that "</scr" + "ipt>" can be used instead.
Adding the sourceURL in the script file helped as mentioned in this page:
https://blog.getfirebug.com/2009/08/11/give-your-eval-a-name-with-sourceurl/
In the script file, add a statement with sourceURL like "//# sourceURL=foo.js"
Load the script using jQuery $.getScript() and the script will be available in "sources" tab in chrome dev tools
Your script is executing , you just can't use document.write from it. Use an alert to test it and avoid using document.write. The statements of your js file with document.write will not be executed and the rest of the function will be executed.
This is what I think is the best solution. Google Analytics is injected this way.
var (function(){
var p="https:" == document.location.protocol ? "https://" : "http://";
d=document,
g=d.createElement('script'),
s=d.getElementsByTagName('script')[0];
g.type='text/javascript';
g.src=p+'url-to-your-script.js';
s.parentNode.insertBefore(g,s); })();
You don't need jQuery to create a Script DOM Element. It can be done with vanilla ES6 like so:
const script = "console.log('Did it work?')"
new Promise((resolve, reject) => {
(function(i,s,o,g,r,a,m){
a=s.createElement(o),m=s.getElementsByTagName(o)[0];
a.innerText=g;
a.onload=r;m.parentNode.insertBefore(a,m)}
)(window,document,'script',script, resolve())
}).then(() => console.log('Sure did!'))
It doesn't need to be wrapped in a Promise, but doing so allows you to resolve the promise when the script loads, helping prevent race conditions for long-running scripts.
Append script to body:
$(document).ready(function() {
$("<script>", { src : "bootstrap.min.js", type : "text/javascript" }).appendTo("body");
});
Another way you can do it if you want to append code is using the document.createElement method but then using .innerHTML instead of .src.
var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.innerHTML = 'alert("Hey there... you just appended this script to the body");';
$("body").append( script );
I tried this one and works fine. Just replace the < symbol with that \x3C.
// With Variable
var code = "\x3Cscript>SomeCode\x3C/script>";
$("#someElement").append(code);
or
//Without Variable
$("#someElement").append("\x3Cscript>SomeCode\x3C/script>");
You can test the code here.
Can try like this
var code = "<script></" + "script>";
$("#someElement").append(code);
The only reason you can't do "<script></script>" is because the string isn't allowed inside javascript because the DOM layer can't parse what's js and what's HTML.
I wrote an npm package that lets you take an HTML string, including script tags and append it to a container while executing the scripts
Example:
import appendHtml from 'appendhtml';
const html = '<p>Hello</p><script src="some_js_file.js"></script>';
const container = document.getElementById('some-div');
await appendHtml(html, container);
// appendHtml returns a Promise, some_js_file.js is now loaded and executed (note the await)
Find it here: https://www.npmjs.com/package/appendhtml
Just create an element by parsing it with jQuery.
<div id="someElement"></div>
<script>
var code = "<script>alert(123);<\/script>";
$("#someElement").append($(code));
</script>
Working example: https://plnkr.co/edit/V2FE28Q2eBrJoJ6PUEBz

Avoiding jQuery conflicts in a dynamically loaded JavaScript application

I am currently trying to develop a JavaScript application that can be embedded in an existing webpage (which I cannot modify). The application needs a specific version of jQuery.
The script used for loading the application is doing the following:
// loading JavaScript needed by my application
(function () {
document.write('<script src="../jquery-1.10.2.min.js"></script>');
document.write(...); // load other scripts (using jQuery 1.10.2)
// storing the application's jQuery in a new namespace
// to avoid conflicts with other jQuery versions
document.write('<script type="text/javascript">' +
'appJQ = jQuery.noConflict(true);</script>'); // error: jQuery is undefined in IE<10
})();
// initializing the application itself
document.onload = function() {
// ...
};
This works fine in every browser I've tested, except IE < 10. In IE 9 and lower I am getting the error that jQuery is undefined.
Moving jQuery to a new namespace in the document.onload function would work for my application but causes conflicts with other scripts on the webpage that includes my application if they need a different version of jQuery.
Do you have any suggestions how to solve this problem?
Thanks for your help!
Instead of using document.write, try creating a <script> element and defining an onload handler for that element:
(function () {
var script = document.createElement('script');
script.src = '//cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js';
script.onload = function() {
var appJQ = jQuery.noConflict(true);
// app initialization code
};
var head = document.head || document.getElementsByTagName('head')[0];
head.appendChild(script);
})();
If you have multiple scripts that depend on one another, you might want to try using a script loader such as HeadJS or LABjs.
If you want even greater flexibility in managing dependencies, you can try using a module loader such as RequireJS, Browserify, or webpack.
Following Hamza's answer, you can use this method of loading in a different way:
var s = document.createElement("script");
s.src = "../jquery.min.js" // insert your own jQuery link
s.onload = function() {
var appJS = jQuery.noConflict(true);
}
Hope this helps.
The document.write calls would also happen after the document is considered loaded, in which case your onload function might fire before the contents of that first function. You want to load the javascript files in a better way, such that their onload initiates the application itself.

How to include jQuery in remote Javascript file only if site doesn't have jQuery?

I have a script (embed.js) that is being included from other websites/domains. Ex:
<script type="text/javascript" src="//mydomain.com/embed.js"></script>
The code in this script relies on jQuery, but obviously not every website uses jQuery. So, I put this code in the embed.js script at the top:
if (typeof jQuery == 'undefined') {
var jq = document.createElement('script');
jq.type = 'text/javascript';
jq.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js';
document.getElementsByTagName('head')[0].appendChild(jq);
jQuery.noConflict();
}
But, I get an error about "jQuery" not being defined for the noConflict() line. It is indeed adding the jQuery tag/code to the page, but for some reason after that appendChild() line, the following noConflict() line doesn't recognize jQuery.
How do I only include jQuery on a page if it's not already on it, through a remote Javascript file, and then in that same Javascript file use that jQuery I just included? (This all needs to be through one file.)
You are getting the error because the method you're using for loading jQuery loads it asynchronously, thus jQuery is not yet loaded when you try to execute the .noConflict() line.
You would have similar problems if your code is also trying to use jQuery as it initializes (if your code isn't also loading asynchronously).
If you need to load jQuery synchronously (simpler solution, but probably not preferred), then you can use document.write() to actually write the script tag that would load it and the browser will process that synchronously.
You can also load jQuery in a way that will notify you when it is actually loaded at which time you can run the .noConflict() line and then call your own initialization code that uses jQuery. This is probably the most self-contained mechanism and avoids document.write() which can slow down the loading process some in modern browsers (use of document.write() in some circumstances prevents some loading optimizations).
For example, you could load jQuery with this function and then it would call your callback when it was loaded successfully:
function loadScript(sScriptSrc, oCallback) {
var oHead = document.getElementsByTagName('head')[0];
var oScript = document.createElement('script');
oScript.type = 'text/javascript';
oScript.src = sScriptSrc;
// most browsers
oScript.onload = oCallback;
// IE 6 & 7
oScript.onreadystatechange = function() {
if (this.readyState == 'complete') {
oCallback();
}
}
oHead.appendChild(oScript);
}
loadScript("jquery.js", function() {
jQuery.noConflict();
// call your own initialization function that uses jQuery here
});

Managing third party javascript libraries with bundled jQuery

I am working on a website globalization project, which involves (us the vendor) asking our clients to insert a script tag on their home/origin site. The script tag is necessary for helping our clients go global, and part of the solution embodies a UI that gets triggered based on certain end user criteria.
The UI is built through the help of jQuery, which we really can't expect our clients to insert on their pages, not to mention version mismatches will be hard to resolve. Therefore, our third party library downloads its own jQuery version, albeit namespaced differently to avoid any conflicts.
However, such a mechanism requires us to rename all instances of jQuery to something that will help us avoid name clashes with another jQuery instance (if present), and makes the our mangled jQuery (MY_Query in examples below) very hard to manage, let alone upgrade.
For example
jQuery = window.jQuery = window.$ = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context );
},
.
.
.
jQuery.fn = jQuery.prototype = ...
becomes
MY_JQuery = window.MY_JQuery = window.MY_Q = function( selector, context ) {
// The MY_JQuery object is actually just the init constructor 'enhanced'
return new MY_JQuery.fn.init( selector, context );
},
.
.
.
MP_JQuery.fn = MP_JQuery.prototype = ...
In an ideal world, both us and the client would have a single version of jQuery on the site, and we both would use it to our advantage. But that would mean an upgrade of jQuery would require heavy testing on both sides (while the mangled jQuery version is contained) and that any plugin wanted would require the client to add appropriate script tags to their site, spurring a political debate between the two parties on what versions win.
So, can I manage our jQuery version (with plugins) on a client site without having to rename all instances of jQuery with something like MY_Query with the constraints mentioned above?
Why not check to see if they have jQuery already included on the page and if not dynamically load it? If you know the base level jQuery needed you can check for that like this:
if( !jQuery || !jQuery.fn.jquery === "1.4.4"){
var url = "http://code.jquery.com/jquery-1.4.4.js";
var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.src = url;
document.body.appendChild(script);
}
You'd probably want to improve the version detection to make sure that it doesn't have a version after 1.4.4, but I'm sure you could write the code for that yourself ;-)
==== Edit based on feedback
So you need to maintain multiple versions of jquery on the page. Have you tried something like this:
var original_jquery = $().noConflict();
original_jquery.getScript("http://code.jquery.com/jquery-1.4.4.js");
var new_jquery = $().noConflict();
window.$ = original_jquery;
Then use the new_jquery as your version of jquery? I haven't tested this to see if it would work, but you might have some luck with it.
==== Final edit
As you mentioned, my javascript above wasn't exactly correct, so I tried out a few things in the console. And yes, you don't need to save the old version of jQuery because jQuery does that in the noConflict method. So just call getScript, then noConflict but saving to a new variable:
>> $.fn.jquery
"1.4.2"
>> $.getScript("http://code.jquery.com/jquery-1.4.4.js");
undefined
>> $.fn.jquery
"1.4.4"
>> var new_jquery = $.noConflict();
undefined
>> new_jquery.fn.jquery
"1.4.4"
>> $.fn.jquery
"1.4.2"
Have you tried to use JQuery.noConflict(). This sounds like it could help you.

Can't append <script> element

Any idea why the piece of code below does not add the script element to the DOM?
var code = "<script></script>";
$("#someElement").append(code);
The Good News is:
It's 100% working.
Just add something inside the script tag such as alert('voila!');. The right question you might want to ask perhaps, "Why didn't I see it in the DOM?".
Karl Swedberg has made a nice explanation to visitor's comment in jQuery API site. I don't want to repeat all his words, you can read directly there here (I found it hard to navigate through the comments there).
All of jQuery's insertion methods use
a domManip function internally to
clean/process elements before and
after they are inserted into the DOM.
One of the things the domManip
function does is pull out any script
elements about to be inserted and run
them through an "evalScript routine"
rather than inject them with the rest
of the DOM fragment. It inserts the
scripts separately, evaluates them,
and then removes them from the DOM.
I believe that one of the reasons jQuery
does this is to avoid "Permission
Denied" errors that can occur in
Internet Explorer when inserting
scripts under certain circumstances.
It also avoids repeatedly
inserting/evaluating the same script
(which could potentially cause
problems) if it is within a containing
element that you are inserting and
then moving around the DOM.
The next thing is, I'll summarize what's the bad news by using .append() function to add a script.
And The Bad News is..
You can't debug your code.
I'm not joking, even if you add debugger; keyword between the line you want to set as breakpoint, you'll be end up getting only the call stack of the object without seeing the breakpoint on the source code, (not to mention that this keyword only works in webkit browser, all other major browsers seems to omit this keyword).
If you fully understand what your code does, than this will be a minor drawback. But if you don't, you will end up adding a debugger; keyword all over the place just to find out what's wrong with your (or my) code. Anyway, there's an alternative, don't forget that javascript can natively manipulate HTML DOM.
Workaround.
Use javascript (not jQuery) to manipulate HTML DOM
If you don't want to lose debugging capability, than you can use javascript native HTML DOM manipulation. Consider this example:
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "path/to/your/javascript.js"; // use this for linked script
script.text = "alert('voila!');" // use this for inline script
document.body.appendChild(script);
There it is, just like the old days isn't it. And don't forget to clean things up whether in the DOM or in the memory for all object that's referenced and not needed anymore to prevent memory leaks. You can consider this code to clean things up:
document.body.removechild(document.body.lastChild);
delete UnusedReferencedObjects; // replace UnusedReferencedObject with any object you created in the script you load.
The drawback from this workaround is that you may accidentally add a duplicate script, and that's bad. From here you can slightly mimic .append() function by adding an object verification before adding, and removing the script from the DOM right after it was added. Consider this example:
function AddScript(url, object){
if (object != null){
// add script
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "path/to/your/javascript.js";
document.body.appendChild(script);
// remove from the dom
document.body.removeChild(document.body.lastChild);
return true;
} else {
return false;
};
};
function DeleteObject(UnusedReferencedObjects) {
delete UnusedReferencedObjects;
}
This way, you can add script with debugging capability while safe from script duplicity. This is just a prototype, you can expand for whatever you want it to be. I have been using this approach and quite satisfied with this. Sure enough I will never use jQuery .append() to add a script.
I've seen issues where some browsers don't respect some changes when you do them directly (by which I mean creating the HTML from text like you're trying with the script tag), but when you do them with built-in commands things go better. Try this:
var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.src = url;
$("#someElement").append( script );
From: JSON for jQuery
It is possible to dynamically load a JavaScript file using the jQuery function getScript
$.getScript('http://www.whatever.com/shareprice/shareprice.js', function() {
Display.sharePrice();
});
Now the external script will be called, and if it cannot be loaded it will gracefully degrade.
What do you mean "not working"?
jQuery detects that you're trying to create a SCRIPT element and will automatically run the contents of the element within the global context. Are you telling me that this doesn't work for you? -
$('#someElement').append('<script>alert("WORKING");</script>');
Edit: If you're not seeing the SCRIPT element in the DOM (in Firebug for example) after you run the command that's because jQuery, like I said, will run the code and then will delete the SCRIPT element - I believe that SCRIPT elements are always appended to the body... but anyway - placement has absolutely no bearing on code execution in this situation.
This works:
$('body').append($("<script>alert('Hi!');<\/script>")[0]);
It seems like jQuery is doing something clever with scripts so you need to append the html element rather than jQuery object.
Try this may be helpful:
var fileref=document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src","scriptAnalytics.js");
document.getElementsByTagName("head")[0].appendChild(fileref);
I want to do the same thing but to append a script tag in other frame!
var url = 'library.js';
var script = window.parent.frames[1].document.createElement('script' );
script.type = 'text/javascript';
script.src = url;
$('head',window.parent.frames[1].document).append(script);
<script>
...
...jQuery("<script></script>")...
...
</script>
The </script> within the string literal terminates the entire script, to avoid that "</scr" + "ipt>" can be used instead.
Adding the sourceURL in the script file helped as mentioned in this page:
https://blog.getfirebug.com/2009/08/11/give-your-eval-a-name-with-sourceurl/
In the script file, add a statement with sourceURL like "//# sourceURL=foo.js"
Load the script using jQuery $.getScript() and the script will be available in "sources" tab in chrome dev tools
Your script is executing , you just can't use document.write from it. Use an alert to test it and avoid using document.write. The statements of your js file with document.write will not be executed and the rest of the function will be executed.
This is what I think is the best solution. Google Analytics is injected this way.
var (function(){
var p="https:" == document.location.protocol ? "https://" : "http://";
d=document,
g=d.createElement('script'),
s=d.getElementsByTagName('script')[0];
g.type='text/javascript';
g.src=p+'url-to-your-script.js';
s.parentNode.insertBefore(g,s); })();
You don't need jQuery to create a Script DOM Element. It can be done with vanilla ES6 like so:
const script = "console.log('Did it work?')"
new Promise((resolve, reject) => {
(function(i,s,o,g,r,a,m){
a=s.createElement(o),m=s.getElementsByTagName(o)[0];
a.innerText=g;
a.onload=r;m.parentNode.insertBefore(a,m)}
)(window,document,'script',script, resolve())
}).then(() => console.log('Sure did!'))
It doesn't need to be wrapped in a Promise, but doing so allows you to resolve the promise when the script loads, helping prevent race conditions for long-running scripts.
Append script to body:
$(document).ready(function() {
$("<script>", { src : "bootstrap.min.js", type : "text/javascript" }).appendTo("body");
});
Another way you can do it if you want to append code is using the document.createElement method but then using .innerHTML instead of .src.
var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.innerHTML = 'alert("Hey there... you just appended this script to the body");';
$("body").append( script );
I tried this one and works fine. Just replace the < symbol with that \x3C.
// With Variable
var code = "\x3Cscript>SomeCode\x3C/script>";
$("#someElement").append(code);
or
//Without Variable
$("#someElement").append("\x3Cscript>SomeCode\x3C/script>");
You can test the code here.
Can try like this
var code = "<script></" + "script>";
$("#someElement").append(code);
The only reason you can't do "<script></script>" is because the string isn't allowed inside javascript because the DOM layer can't parse what's js and what's HTML.
I wrote an npm package that lets you take an HTML string, including script tags and append it to a container while executing the scripts
Example:
import appendHtml from 'appendhtml';
const html = '<p>Hello</p><script src="some_js_file.js"></script>';
const container = document.getElementById('some-div');
await appendHtml(html, container);
// appendHtml returns a Promise, some_js_file.js is now loaded and executed (note the await)
Find it here: https://www.npmjs.com/package/appendhtml
Just create an element by parsing it with jQuery.
<div id="someElement"></div>
<script>
var code = "<script>alert(123);<\/script>";
$("#someElement").append($(code));
</script>
Working example: https://plnkr.co/edit/V2FE28Q2eBrJoJ6PUEBz

Categories

Resources