JSFiddle wrap in onLoad?

蓝咒 提交于 2019-11-30 07:34:17

问题


I'm trying to understand how JSFiddle 'wraps' code in 'onLoad' based on this description: [1]: http://doc.jsfiddle.net/basic/introduction.html#javascript. I've seen onLoad being used in the HTML's BODY tag to load function(s). So does JSF (behind the scenes) wrap every call and every function I create int its JS window? AKA:

onLoad = "myfunc1(),myfunc2,alert(1);" 

If so then when I select jQuery as a framework, should I avoid using this format:

 $(document).ready(function(){
     myfunc1{(...)}
     myfunc1{(...)}
     ...

Apologize in advance if an armature question.


回答1:


They put all your JS inside <script> tags with the onLoad event code wrapped around it.

For example, if you choose to include jQuery and onLoad then this is what jsfiddle will use:

<script type="text/javascript">
    //<![CDATA[
        $(window).load(function(){ /* your js here */ });
    //]]>
</script>

If you don't include a library then they use:

<script type="text/javascript">
    //<![CDATA[
        window.onload=function(){ /* your js here */ }
    //]]>
</script>

I presume they also use other library specific load events depending on what you choose to include.

Using $(document).ready(function(){ }); isn't required when running your code in a fiddle.

Note: for a good explanation of what CDATA is take a look at this answer - https://stackoverflow.com/a/7092306/2287470




回答2:


It makes a new iframe to run your code in.

For the onload, they just put all your code in

window.onload = function () {
    // your code here
};

You can see this if you inspect the <script> tag in the <head> of the bottom-right iframe.


Nothing wrong with using $(document).ready(... but it's kinda useless when you enable the onLoad option in jsFiddle.




回答3:


if you are looking for source code formatting, then you should look for site like below. As to what jsfiddle use they might have their own plugins which does the same.

http://jsbeautifier.org/

http://www.javascriptbeautifier.com/

http://www.jspretty.com/



来源:https://stackoverflow.com/questions/19203922/jsfiddle-wrap-in-onload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!